美文网首页
python 阿姆斯特朗数(水仙花数)

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

作者: 吃鱼喵了个鱼 | 来源:发表于2019-06-02 13:39 被阅读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
    

    相关文章

      网友评论

          本文标题:python 阿姆斯特朗数(水仙花数)

          本文链接:https://www.haomeiwen.com/subject/vrrxxctx.html