问题:
“水仙花数”是指一个三位数其各位数字的立方和等于该数本身,例如153是“水仙花数”,因为: 153 = 1 3 + 5 3 + 3 3 153 = 1^{3}+ 5^{3} + 3^{3} 153=13+53+33。输出 100 ∼ 999 100sim999 100∼999 之间的所有水仙花数。
方法一:
#include<iostream> using namespace std; int main(){int a = 0;for (int x = 1; x<10; x++){for (int y = 0; y<10; y++){for (int z = 0; z<10; z++){a = 100 * x + 10 * y + z;if (a == x*x*x + y*y*y + z*z*z) cout << a << endl;}}}return 0; } 123456789101112131415
方法二:
#include<iostream> using namespace std; int main(){int x = 0;int y = 0;int z = 0;for (int n = 100; n<1000; n++){x = n / 100;y = (n % 100) / 10;z = n % 10;if (n == x*x*x + y*y*y + z*z*z) cout << n << endl;}return 0; } 123456789101112131415