c语言水仙花数

7-93 水仙花数 (20分)
水仙花数是指一个N位正整数(N≥3),它的每个位上的数字的N次幂之和等于它本身。例如:

153 = 1 3 + 5 3 + 3 3 . 153=1^3+5^3+3^3.

​​本题要求编写程序,计算所有N位水仙花数。

输入格式:
输入在一行中给出一个正整数N(3≤N≤6)。

输出格式:
按递增顺序输出所有N位水仙花数,每个数字占一行。

输入样例:

3

输出样例:

153
370
371
407

给出一个具体的位数n,我们应该首先找出所有的n位数,然后从末位开始分割,直到分割完全。

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

int main()
{
    int N,i;
    int t,z=0;
    scanf("%d",&N);
    int a=pow(10,N-1);
    int b=pow(10,N);
    for (i=a;i<b;i++){   //a,b之间就是所有的n位数
        z=i;t=0;
        while (z>0)   
        {
            t +=pow(z%10,N);  //从末位开始分割
            z /=10;  //每次缩减一位
        }if (i==t){
            printf("%d\n",i);  //判断是否属于水仙花数
        }
    }    
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_46530492/article/details/105727630