C++和python實(shí)現(xiàn)阿姆斯特朗數(shù)字查找實(shí)例代碼
如果一個(gè)n位正整數(shù)等于其各位數(shù)字的n次方之和,則稱該數(shù)為阿姆斯特朗數(shù)。 例如1^3 + 5^3 + 3^3 = 153。
1000以內(nèi)的阿姆斯特朗數(shù): 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407
2.判斷一個(gè)數(shù)是否為阿姆斯特朗數(shù)1.先來一個(gè)簡單的代碼,判斷一個(gè)數(shù)是否為阿姆斯特朗數(shù);
來看看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%10; sum=sum+(r*r*r); n=n/10; } if(temp==sum) cout<<'Armstrong Number.'<<endl; else cout<<'Not Armstrong Number.'<<endl; return 0;}
運(yùn)行結(jié)果:
接下來看看Python
num = int(input('請輸入一個(gè)數(shù)字:'))sum= 0n = len(str(num))temp = numwhile temp >0: digit = temp %10 # 獲取個(gè)位數(shù)字 sum += digit**n # 對計(jì)算結(jié)果進(jìn)行累加 temp //= 10if num == sum : print('太棒了!',num,'是阿姆斯特朗數(shù)')else: print('很遺憾!',num,'不是阿姆斯特朗數(shù)')
運(yùn)行結(jié)果:
python實(shí)現(xiàn):
lower = int(input('最小值:'))upper = int(input('最大值:'))print('下面是你想要從{}到{}之間的阿姆斯特朗數(shù)n'.format(lower,upper))for num in range(lower,upper+1): sum = 0 n = len(str(num)) temp = num while temp >0: digit = temp %10 # 獲取個(gè)位數(shù)字 sum+= digit**n # 對計(jì)算結(jié)果進(jìn)行累加 temp //= 10 if num == sum: print(num)
運(yùn)行結(jié)果:
C++實(shí)現(xiàn):
#include <iostream>using namespace std;int test(int a,int b,int c,int d){if(a)return a*a*a*a+b*b*b*b*b+c*c*c*c+d*d*d*d*d;if(b)return b*b*b+c*c*c+d*d*d;if(c)return c*c+d*d;if(d)return d;}void func(int min, int max){if(min<=0||min>=max||max<0||max>9999){cout << 'error!' << endl;}int a,b,c,d;for(int i=min;i<=max;i++){a = i/1000;b = (i%1000)/100;c = (i%100)/10;d = i%10;if(i==test(a,b,c,d))cout << i << endl;}}int main(){int min,max;cin >> min;cin >> max;func(min,max);system('pause');return 0;}
運(yùn)行結(jié)果展示:
C++太復(fù)雜了,就不能向python學(xué)學(xué),多友好的語言,學(xué)C++心態(tài)炸裂的第二天,如果有幫助到你點(diǎn)個(gè)關(guān)注唄!
到此這篇關(guān)于C++和python實(shí)現(xiàn)阿姆斯特朗數(shù)字查找的文章就介紹到這了,更多相關(guān)C++和python阿姆斯特朗數(shù)字查找內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 愛因斯坦謎題的java解答方法2. PHP腳本的10個(gè)技巧(8)3. idea自定義快捷鍵的方法步驟4. Springboot整合camunda+mysql的集成流程分析5. python中復(fù)數(shù)的共軛復(fù)數(shù)知識點(diǎn)總結(jié)6. PHP中file_get_contents設(shè)置header請求頭,curl傳輸選項(xiàng)參數(shù)詳解說明7. IntelliJ IDEA設(shè)置默認(rèn)瀏覽器的方法8. html清除浮動的6種方法示例9. jsp網(wǎng)頁實(shí)現(xiàn)貪吃蛇小游戲10. python 實(shí)現(xiàn)在無序數(shù)組中找到中位數(shù)方法
