判断任意控制台输入十进制数是否为水仙花数(C++)

背景知识:

数论中,水仙花数Narcissistic number)也称为自恋数自幂数阿姆斯壮数阿姆斯特朗数Armstrong number),是指一N位数,其各个数之N次方和等于该数。

例如153、370、371及407就是三位数的水仙花数,其各个数之立方和等于该数:

153 = 13 + 53 + 33
370 = 33 + 73 + 03
371 = 33 + 73 + 13
407 = 43 + 03 + 73

具体定义为:

设有个自然数n,n = dkdk-1...d1d0其中k是n的位数,而 di 的范围是 0 ≤ di ≤ 9,如果n满足以下条件,则称它为水仙花数

n = dkk + dk-1k + ... + d2k + d1k.

 

以下为c++代码:

 1 #include <iostream>
 2 #include <conio.h>
 3 #include <math.h>
 4 using namespace std;
 5 void main()
 6 {
 7     int a,b=0,sum=0;
 8     long int n;
 9     cout<<"Please Enter a No:"<<endl;
10     cin>>n;
11     for(long int l=n;l>0;)
12     //counts the digits
13     {
14         a=l%10;
15         l=l/10;
16         b++;
17     }
18     for(long int m=n;m>0;)
19     {
20         a=m%10;
21         sum=sum+pow((float)a,b);
22         m=m/10;
23     }
24     if(sum==n)
25     {
26         cout<<"This is an Amstrong Number!\n";
27         getch();
28     }
29     else
30     {
31         cout<<"This is not an Amstrong Number!\n";
32         getch();
33     }
34 }


一年之后,我会非常庆幸自己今天选择了开始。 当我觉得为时已晚的时候,恰恰是最早的时候。 It does not matter how slow I go so long as I do not stop.
原文地址:https://www.cnblogs.com/techpalm/p/2910936.html