C语言:判断0~999之间的水仙花数,并打印出来。

“水仙花数”是指一个N位数,其各个数字的N次方和确好等于该数本身,如;153=1+5+3,则153是一个“水仙花数”。水仙花数(Narcissistic number)也称为自恋数、自幂数、阿姆斯壮数或阿姆斯特朗数(Armstrong number),是指一N位数,其各个数之N次方和等于该数。

    例如153、370、371及407就是三位数的水仙花数,其各个数之立方和等于该数:
153 = 1^3 + 5^3 + 3^3。
370 = 3^3 + 7^3 + 0^3。
371 = 3^3 + 7^3 + 1^3。
407 = 4^3 + 0^3 + 7^3。

# include <stdio.h>

# include <stdlib.h>
# include <math.h>
int main()
{
	int i = 0;
	for (i = 0; i <= 999; i++)
	{
		//i是否为水仙花数
		//①确定i是几位数
		int n = 1;
		int sum = 0;
		int tmp = i;
		while (tmp / 10)
		{
			n++;
			tmp = tmp / 10;
		}
     //②拆下i的每一位并计算和
		tmp = i;
		while (tmp)
		{
			sum = sum + pow(tmp%10, n);
			tmp = tmp / 10;
		}
		//③判断
		if (sum == i)
		{
			printf("%d  ",i);
		}
	}
	system("pause");
	return 0

运行结果截图:


猜你喜欢

转载自blog.csdn.net/qq_42270373/article/details/80578115