c++水仙花数 不知道错在哪😩

img


#include
#include
using namespace std;

int main() {
int N;//N是位数
cin >> N;
for (int tot = pow(10, N - 1); tot < pow(10, N); tot++) {

    while (tot != 0) {
        int sum = 0;
        int temp;
        temp = tot % 10;
        tot = tot / 10;
        int squ = pow(temp, N);
        sum += squ;
    }
    if (sum == tot) {
        cout << tot << endl;

    }
}

}

return 0;
}

你应该sum定义为全局变量不然if语句中的sum无法被访问到,然后每一次for循环结束后再将sum赋值为0