Python程序检查一个数字是否阿姆斯特朗不工作,我做错了什么?

2024-06-01 00:12:51 发布

您现在位置:Python中文网/ 问答频道 /正文

n=int(input("Enter a Number: "))
x=0
y=0
z=0

while(n>0):
    x=n%10
    y=x**3
    z=z+y
    n=n//10

print (z) 


#The z here is the same value which I enter, yet it doesn't work.
#If I enter 407 as n, z becomes (4^3)+(0^3)+(7^3) which is 407

 if (z==n): 

#But even when 407==407, it just wont print the bottom statement


    print ("The number is Armstrong")
else:
    print ("The number isn't Armstrong")
 #it prints that it isn't an Armstrong number

Tags: thenumberwhichinputisitintarmstrong
3条回答

不使用任何内置方法

阿姆斯特朗数是371,因为3**3 + 7**3 + 1**3 = 371。根据这个规则,123不是阿姆斯特朗数,因为1**3 + 2**3 + 3**3 is not equal to 123

def count_digit(n):
    count = 0
    while n > 0:
        count += 1
        n //= 10
    return count

def is_armstrong(n):
    given = n
    result = 0
    digit = count_digit(n)
    while n > 0:
        reminder = n % 10
        result += reminder ** digit
        n //= 10 
    return given == result
^{pr2}$

while循环之后,n已经变成了4//10,即0,因此它永远不会等于407。在

您需要保留原始输入的副本以供比较。在

{或者至少把cd6>作为一个通用的调试程序使用。在

你可以把你的初始数字作为一个字符串,这样我们就可以更容易地把它转换成一个列表。然后我们可以map来创建{}的列表。然后我们可以使用列表理解将该列表中的所有int提升为列表的len的幂次。如果这个列表的sum等于我们的输入,那么我们有一个Armstrong数。在

n = input('Enter a number: ')
nums = list(map(int, n))
raised = [i**len(nums) for i in nums]
if sum(raised) == int(n):
    print('The number is Armstrong')
else:
    print('The number is not Armstrong')

扩展列表理解:

^{pr2}$

替代map

^{3}$

相关问题 更多 >