首页 > 解决方案 > Armstrong 数字的 Python 程序未正确输出

问题描述

 def order(x):
    n=0
    while(x>0):
        n=n+1
        x=x/10
    return n




 def isArmstrong(x):
     n=order(x)
     print(n)
     temp=x
     sum1=0
     while(temp!=0):
         r=temp%10
         sum1=sum1+pow(r,n)
         temp=temp/10

     return (sum1==x)

x=int(input("Enter a number: "))
print(isArmstrong(x))


标签: python

解决方案


你没有取整数,而是取一些实数来满足你的条件。所以这是你犯的小错误。

我做了一些更正

x/10-->x//10

temp=temp//10-->temp=temp//10


 def order(x):
    n=0

    while(x>0):
        n=n+1
        x=x//10 # <-------- Here
    return n




 def isArmstrong(x):
     n=order(x)
     temp=x
     sum1=0
     while(temp!=0):
         r=temp%10
         sum1=sum1+pow(r,n)
         temp=temp//10 # <----------- Here

     return (sum1==x)

x=int(input("Enter a number: "))
print(isArmstrong(x))

结果:


Enter a number: 100
False

Enter a number: 370
True

推荐阅读