国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術(shù)文章
文章詳情頁

C++和python實(shí)現(xiàn)阿姆斯特朗數(shù)字查找實(shí)例代碼

瀏覽:120日期:2022-07-02 18:53:33
1.題目解釋

如果一個(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è)簡(jiǎn)單的代碼,判斷一個(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é)果:

C++和python實(shí)現(xiàn)阿姆斯特朗數(shù)字查找實(shí)例代碼

接下來看看Python

num = int(input('請(qǐng)輸入一個(gè)數(shù)字:'))sum= 0n = len(str(num))temp = numwhile temp >0: digit = temp %10 # 獲取個(gè)位數(shù)字 sum += digit**n # 對(duì)計(jì)算結(jié)果進(jìn)行累加 temp //= 10if num == sum : print('太棒了!',num,'是阿姆斯特朗數(shù)')else: print('很遺憾!',num,'不是阿姆斯特朗數(shù)')

運(yùn)行結(jié)果:

C++和python實(shí)現(xiàn)阿姆斯特朗數(shù)字查找實(shí)例代碼

2.寫一個(gè)查找固定范圍內(nèi)的阿姆斯特朗數(shù)

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 # 對(duì)計(jì)算結(jié)果進(jìn)行累加 temp //= 10 if num == sum: print(num)

運(yùn)行結(jié)果:

C++和python實(shí)現(xiàn)阿姆斯特朗數(shù)字查找實(shí)例代碼

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++和python實(shí)現(xiàn)阿姆斯特朗數(shù)字查找實(shí)例代碼

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)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!

標(biāo)簽: Python 編程
相關(guān)文章:
主站蜘蛛池模板: 灌南县| 西畴县| 霸州市| 新龙县| 德清县| 盐津县| 东乡| 山东| 商南县| 徐汇区| 蒙城县| 黑龙江省| 林州市| 莱西市| 望都县| 贵溪市| 蕉岭县| 扬中市| 凤台县| 禹州市| 内乡县| 依兰县| 祁东县| 洛阳市| 石狮市| 老河口市| 河东区| 刚察县| 香格里拉县| 白城市| 江华| 宣汉县| 阳曲县| 河北省| 普宁市| 康保县| 南开区| 长阳| 华阴市| 原平市| 昔阳县|