求出0〜999之间的所有“水仙花数”并输出。



水仙花数是指一个 n 位数 ,它的每个位上的数字的 n 次幂之和等于它本身。在数论中,水仙花数(Narcissistic number)也称为自恋数、自幂数、阿姆斯壮数或阿姆斯特朗数(Armstrong number)。
例如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
#include
#include
int isWaterFlower(int x)
{
	int n = 0;
	int sum = 0;
	int y = x;
	if (x >=0&&x <=10)//判断是几位数。
	{
		n=1;
	}
	else if (x >= 10&&x <=100)
	{
		n = 2;
	}
	else if (x >= 100&&x < 10000)
	{
		n = 3;
	}
	else
	{
		printf("error");
		return 0;
	}
	while (x)
	{
		sum += pow(x % 10, n);
		x = x / 10;
	}
	if (y == sum)//一位数字的n次幂的和正好等于这个数本身。
	{
		return 1;
	}
	
		return 0; 
}

int main()
{
	int i = 0;
	for (; i < 1000; i++)
	{
		if (isWaterFlower(i))
		{
			printf("%d\n", i);
		}
	}
	printf("\n");
	system("pause");
	return 0;
}
输出结果为: 求出0〜999之间的所有“水仙花数”并输出。_第1张图片

你可能感兴趣的:(c语言)