久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

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

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

瀏覽:122日期: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è)簡單的代碼,判斷一個(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)文章:
主站蜘蛛池模板: 迭部县| 鄂尔多斯市| 肥城市| 民勤县| 南通市| 吉隆县| 襄汾县| 万载县| 长葛市| 虹口区| 奎屯市| 凌云县| 绥滨县| 久治县| 临泉县| 任丘市| 什邡市| 大洼县| 辉县市| 车致| 麻城市| 大港区| 江西省| 淮阳县| 洛川县| 通州区| 武邑县| 朝阳区| 定州市| 大洼县| 乌鲁木齐市| 沅陵县| 启东市| 彭水| 和林格尔县| 伊金霍洛旗| 佛教| 陆丰市| 武穴市| 澜沧| 德州市|