在编写C++程序以检查数字是否为阿姆斯壮数字之前,先要来了解一下阿姆斯壮数字是什么。
阿姆斯壮数字是等于其数字的立方之和的数字。 例如:0
,1
,153
,370``,371
和407
是阿姆斯壮数字。
下面说明为什么371
是阿姆斯壮数字。
371 = (3*3*3)+(7*7*7)+(1*1*1)
这里:
(3*3*3)=27
(7*7*7)=343
(1*1*1)=1
所以:
27+343+1=371
让我们来看看如何使用C++程序来判断阿姆斯壮数字。
#include <iostream>
using namespace std
int main()
{
int n,r,sum=0,temp
cout<<"Enter the Number= "
cin>>n
temp=n
while(n>0)
{
r=n
sum=sum+(r*r*r)
n=n/10
}
if(temp==sum)
cout<<"Armstrong Number."<<endl
else
cout<<"Not Armstrong Number."<<endl
return 0
}
执行上面代码,得到以下结果 -
Enter the Number= 371
Armstrong Number.
Enter the Number= 342
Not Armstrong Number.