debugging 编了一个程序来检查阿姆斯特朗数,但找不到它的毛病

vnzz0bqm  于 2023-01-02  发布在  其他
关注(0)|答案(2)|浏览(139)

这基本上是检查给定的数字是否是阿姆斯特朗数的代码,但是我不明白为什么我的输出不正确

num = int(input("Enter a number: "))
sum = 0
temp = num
while temp > 0:
   digit = temp % 10
   sum += digit * 3
   temp //= 10
if num == sum:
   print(num,"is an Armstrong number")
else:
   print(num,"is not an Armstrong number")

输出不正确

sd2nnvve

sd2nnvve1#

获取总位数并应用pow()函数

num = int(input("Enter a number: "))
num_digits = len(str(num))
sum = 0
temp = num
while temp > 0:
   digit = temp % 10
   sum += pow(digit, num_digits)
   temp //= 10
if num == sum:
   print(num,"is an Armstrong number")
else:
   print(num,"is not an Armstrong number")
xa9qqrwz

xa9qqrwz2#

您的算法错误。行:

sum += digit * 3

...应该是...

sum += digit ** 3

这显然是您的意图。但是,这只适用于3位数。一般方法可以这样实现:

from math import log10

def isArmstrong(n):
    _len = int(log10(n)) + 1
    _n = n
    _sum = 0
    while (_n > 0):
        _sum += (_n % 10) ** _len
        _n //= 10
    return _sum == n

示例:

# all values from 1-9 are Armstrong numbers so start from 10
for i in range(10, 1_000_000):
    if isArmstrong(i):
        print(i)

输出:

153
370
371
407
1634
8208
9474
54748
92727
93084
548834

相关问题