所谓水仙花数(NarcissisticNumber)是指一个3位数,其各位数字的立方和等于它本身。
思路:(1)将该数各位数字分解出来,然后求各数字立方和是否等于原数
(2)凑3个数字,组成一个三位数,求各数字立方和是否等于凑成的数(注意百位数字从1开始)
例如153是“水仙花数”,因为:153 = 13 + 53 + 33。
一、方法1:
#include <iostream>
#include <cmath>
using namespace std;
int main(int argc, const char * argv[]) {
int n, unit, ten, hund; // unit, ten, hund分别存储个位、十位和百位的数字
for(n = 100; n < 1000; n++) {
unit = n % 10; // 得到n的个位数字
ten = (n / 10) % 10; // 得到n的十位数字
hund = n / 100; // 得到n的百位数字
// 判断各位数字的立方和是否等于它本身
if(n == hund * hund * hund + ten * ten * ten + unit * unit * unit)
// if(n == pow(hund, 3) + pow(ten, 3) + pow(unit, 3))
cout << n << " ";
}
cout << endl;
return 0;
}
二、方法2:
#include <iostream>
using namespace std;
int main(int argc, const char * argv[]) {
int sum;
for(int i = 1; i < 10; i++)
for(int j = 0; j < 10; j++)
for(int k = 0; k < 10; k++) {
sum = i * 100 + j * 10 + k;
if(sum == (i * i * i + j * j * j + k * k * k))
cout << sum << " ";
}
cout << endl;
return 0;
}
运行结果: