python 阿姆斯特朗数(水仙花数)

2019-06-02  本文已影响0人  吃鱼喵了个鱼
阿姆斯特朗数:如果一个n位正整数等于其各位数字的n次方之和
#将n位正整数是否等于其各位数字的n次方之和定义在一个函数中
def amuste(low,high):  #形参为要判定的数字范围
    for num in range(low, high + 1):
        sum = 0
        n = len(str(num))   #求正整数的位数
        temp = num
        while temp > 0:
            digit = temp % 10
            sum += digit ** n
            temp //= 10
        if num == sum:
            print(num,end = ' ')

#检查输入是否合理,并调用amuste()函数
while(True):
    try:
        lower = int(input("please input the minimum value: "))
        upper = int(input("please input the maximal value: "))
    except ValueError:
        print("please input a right number!")
        continue
    if lower>upper:
        print("input size incorrect!")
        continue
    amuste(lower,upper)
    break

输出结果为:

please input the minimum value: 1
please input the maximal value: 1000
1 2 3 4 5 6 7 8 9 153 370 371 407
上一篇 下一篇

猜你喜欢

热点阅读