原文: https://www.programiz.com/python-programming/examples/armstrong-number
要理解此示例,您应该了解以下 Python 编程主题:
一个正整数称为阿姆斯特朗数n,如果
abcd... = an + bn + cn + dn + ...对于 3 位的阿姆斯特朗数字,每个数字的立方数之和等于数字本身。 例如:
153 = 1*1*1 + 5*5*5 + 3*3*3 // 153 is an Armstrong number.# Python program to check if the number is an Armstrong number or not
# take input from the user
num = int(input("Enter a number: "))
# initialize sum
sum = 0
# find the sum of the cube of each digit
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10
# display the result
if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number") 输出 1
Enter a number: 663
663 is not an Armstrong number 输出 2
Enter a number: 407
407 is an Armstrong number在这里,我们要求用户输入一个数字,然后检查它是否是一个阿姆斯特朗数字。
我们需要计算每个数字的立方和。 因此,我们将总和初始化为 0,并使用模运算符%获得每个数字。 将数字除以 10 所得的余数是该数字的最后一位。 我们使用指数运算符获取多维数据集。
最后,我们将总和与原始数字进行比较,得出结论,如果它们相等,则为阿姆斯特朗数字。
num = 1634
# Changed num variable to string,
# and calculated the length (number of digits)
order = len(str(num))
# initialize sum
sum = 0
# find the sum of the cube of each digit
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** order
temp //= 10
# display the result
if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number") 您可以在源代码中更改num的值,然后再次运行以对其进行测试。