C语言:输出所有四位水仙花数,并输出四位水仙花数的个数。

C语言:输出所有四位水仙花数,并输出四位水仙花数的个数。水仙花数是指一个 n 位数(n>=3),它的每个位上的数字的 n 次幂之和等于它本身。(例如:1^3 + 5^3 + 3^3 = 153)。

代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>


int main()
{
int i, temp, n, sum, count = 0;

for (i = 1000; i <= 9999; i++) {

temp = i;

sum = 0;

while (temp != 0) {
n = temp % 10;
sum += (int)pow((double)n, 4);
temp /= 10;
}

if (sum == i) {
printf("%d ", i);
count++;
}
}

printf("\n四位数水仙数有 %d 个。\n", count);

system("pause");
return 0;
}

运行结果:

温馨提示:内容为网友见解,仅供参考
第1个回答  2018-04-16
首先你需要引入头文件math.h;然后下面是代码:
int n=1000,num=0;        //num代表水仙花数个数
while(n<10000){
    int a,b,c,d;                    //分别存储个位、十位、百位、千位
    a=n%10;    b=n/10%10;    c=n/100%10;    d=n/1000%10;
    if(pow(a,4)+pow(b,4)+pow(c,4)+pow(d,4)==n){
        printf("%d\t",n)
        num++;
    }
    n++;
}

相似回答