新手上路:求水仙花数 c语言程序

img


为啥只输出370和371 ?望各路大佬帮忙指正


#include <stdio.h>
int main()
{
    int hun, ten, ind, n;
    printf("result is:");
    for( n=100; n<1000; n++ )  /*整数的取值范围*/
    {
        hun = n / 100;
        ten = (n-hun*100) / 10;
        ind = n % 10;
        if(n == hun*hun*hun + ten*ten*ten + ind*ind*ind)  /*各位上的立方和是否与原数n相等*/
            printf("%d  ", n);
    }
    printf("\n");
   
    return 0;
}

img

你不要加else break就可以了,这是原代码问题

然后,我也写了一份给你参考,另一种写法:

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
int main(){
    for(int i=100;i<=999;++i){
        int a=i/100;
        int b=i%100/10;
        int c=i%10;
        if(a*a*a+b*b*b+c*c*c==i)cout<<i<<" "; 
    }
}

问题应该处在else判断语句,break它是直接跳出循环,所以会少记录很多个数,你把else语句删了就行