水仙花数是指一个N位正整数(N≥3),它的每个位上的数字的N次幂之和等于它本身。例如:153=13+53+33。 本题要求编写程序,计算所有N位水仙花数。
输入格式:
输入在一行中给出一个正整数N(3≤N≤7)。
输出格式:
按递增顺序输出所有N位水仙花数,每个数字占一行。
输入示例:
3
输出示例:
153
370
371
407
代码实现
#include<stdio.h>
#include<math.h>
int main(){
int n;
int x;
if (scanf("%d", &n) ==1 ){
for (x = pow(10, n-1);x < pow(10, n) && x >= pow(10, n-1); x++){
int b = x;
int sum = 0;
while(b != 0){
int a = b % 10;//a是余数(从个位开始)
sum += pow(a,n);//sum是单位数的幂运算(从个位开始)
b = b / 10; //x剔除掉已经运算的个位数,重新进入下一轮循环
}
if ( sum == x ){
printf("%d\n", x);
}
}
}
return 0;
}
能够正确运行,但是提交到PTA平台会出现scanf超时报错,不知道为啥
ignoring return value of ‘scanf’, declared with attribute warn_unused_result [-Wunused-result] scanf("%d", &n);