什么是水仙花数?
水仙花数(Narcissistic Number),也被称为自恋数、阿姆斯特朗数(Armstrong Number),是一个 n 位数,它的每个位上的数字的 n 次幂之和等于它本身。例如,一个 3 位数的水仙花数满足以下条件: a b c = a 3 + b 3 + c 3 abc = a^3 + b^3 + c^3 abc=a3+b3+c3。
换句话说,如果一个 n 位数满足: d 1 n + d 2 n + … + d n n = number d_1^n + d_2^n + \ldots + d_n^n = \text{number} d1n+d2n+…+dnn=number,其中 d 1 , d 2 , … , d n d_1, d_2, \ldots, d_n d1,d2,…,dn 是这个数的各个位上的数字,那么这个数就是一个水仙花数。
以下是一些水仙花数的示例:
153 = 1^3 + 5^3 + 3^3
370 = 3^3 + 7^3 + 0^3
371 = 3^3 + 7^3 + 1^3
407 = 4^3 + 0^3 + 7^3
我们要使用 do while 去判断 100-1000的水仙花数有哪些?
do while的语法
//do {循环语句} while (循环条件);
与while区别 会先执行一次循环语句,在判断循环条件
先执行do ,再执行while,条件满足继续do,不满足跳出循环
水仙花数的具体实现
#include<iostream>
using namespace std;
int main()
{
//水仙花数是指一个三位数,他的每个位上的数字的三次幂之和是它本身
//例如: 1^3+5^3+3^3= 153
//请用 do while 语句,求出所有3位数中的水仙花数
int num = 100;
int a = 0;
int b = 0;
int c =0;
do {
a = num % 10; //个位
c = num / 100; //百位
b = (num/10) % 10; //十位
if (num == a*a*a + b*b*b + c*c*c)
{
cout << num << endl;
}
num++;
} while (num < 1000);
system("pause");
return 0;
}