“水仙花数”是指一个n位数,其各位数字的n次方之和确好等于该数本身,如:153=1^3+5^3+3^3,则153是一个“水仙花数”。
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <math.h>
#include <windows.h>
#define M 100000
//“水仙花数”是指一个n位数,其各位数字的n次方之和确好等于该数本身
int main(){
printf("0到%d的水仙花数为:\n", M);
for (int i = 1; i <= M; i++) {
//count来表示水仙花数的位数
int count = 1;//水仙花数至少是一位
int sum = 0;
int temp = i;
while (temp / 10) {
count++;
temp /= 10;
}
temp = i;//重新给temp赋值,因为temp在while循环中已经被修改了
while (temp) {//判断该数是否是水仙花数
//对temp求余是求它的每一位数,再利用pow函数对其每一位求n次方,n为它的位数
sum += pow(temp % 10, count);
//对temp除10是每次将它的最低位除去
temp /= 10;
}
if (i == sum) {
printf("%d\n", sum);
}
}
return 0;
}