问题描述
求水仙花数。
水仙花数就是各位数字的立方和等于该数本身。
例如:水仙花数153
1^3 + 5^3 + 3^3 = 153
算法设计
num除100,得出num的百位数
num除10,再对10求余,得出num的十位数
num对10求余,得出num的个位数
循环判断num是否为水仙花数。
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int num = 100;
do
{
int a=0;
int b=0;
int c=0;
a = num / 100; //百位
b = num / 10 % 10; //十位
c = num % 10; //个位
if (a * a * a +b * b * b + c * c * c == num) //判断该数是否为水仙花数
{
cout << "水仙花数有:" <<num<< endl;
}
num++;
} while (num < 1000); //循环执行条件
return 0;
}
运行结果如下: