这段代码为输出100-999之内的所有“水仙花数”

img


这段代码为输出100-999内所有水仙花数,,水仙花数即指一个三位数,其各位数字立方和等于该数本身

有啥问题要问啊?
第7行要再加一句 result = 0;
因为每次循环判断一个整数是否为水仙数,那么开始时必须将result清零,否则下一个数的result结果会和前一个数的result结果一直累加,自然不对了
result = 0也可以放到14行之后

可以把判断部分,声明为一个函数

int cubicsum(int n)
{
    int sum=0;
    while (n>0)
    {
        sum += (n%10) * (n%10) * (n%10);
        n /= 10;
    }
    return sum==n;
}

修改之后代码如下:

int main(int argc, const char * argv[]) {
    
    int a, result, b;
    for (int i = 100; i < 1000; i++) {
        
        a = i;
        result = 0;
        for (int j = 0; j < 3; j++) {
            
            b = a%10;
            result = result + pow(b, 3);
            a = a/10;
        }
        if (result == i) {

            printf("水仙花数:%d\n", i);
        }
    }
    return 0;
}