找出水仙花数:
首先我们需要了解水仙花数的概念:在数论中,水仙花数(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。
*/
程序要求:需要输出1—10000中的水仙花数
程序分析:
分为两步:1、求出这个数有多少未位,用count记数;
2、将每一位上的数个求count次方求和,与原数据比较。
具体程序实现如下:
int main()
{
int i = 0;
for (i = 1; i < 10000; i++)
{
int count = 0;
int sum = 0;
int tmp = i;
while (tmp)
{
tmp = tmp / 10;//1234 123 12 1
count++;
}
tmp = i;
while (tmp)//1234
{
sum += pow(tmp%10, count);
tmp /= 10;
}
if (sum==i)
{
printf("%d ", i);
}
}
system("pause");
return 0;
}
注意:i是循环变量,不能轻易改变。
所以int tmp=i;这一步是及其重要的。一定不要忘记。