💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、豆包、星火、月之暗面及文生图、文生视频 广告
# Python 程序:检查阿姆斯特朗数 > 原文: [https://www.programiz.com/python-programming/examples/armstrong-number](https://www.programiz.com/python-programming/examples/armstrong-number) #### 在此示例中,您将学习检查 n 位整数是否是阿姆斯特朗数。 要理解此示例,您应该了解以下 [Python 编程](/python-programming "Python tutorial")主题: * [Python `if...else`语句](/python-programming/if-elif-else) * [Python `while`循环](/python-programming/while-loop) * * * 一个正整数称为阿姆斯特朗数`n`,如果 ```py abcd... = an + bn + cn + dn + ... ``` 对于 3 位的阿姆斯特朗数字,每个数字的立方数之和等于数字本身。 例如: ```py 153 = 1*1*1 + 5*5*5 + 3*3*3 // 153 is an Armstrong number. ``` ## 源代码:检查 3 位阿姆斯特朗数 ```py # 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** ```py Enter a number: 663 663 is not an Armstrong number ``` **输出 2** ```py Enter a number: 407 407 is an Armstrong number ``` 在这里,我们要求用户输入一个数字,然后检查它是否是一个阿姆斯特朗数字。 我们需要计算每个数字的立方和。 因此,我们将总和初始化为 0,并使用[模运算符`%`](/python-programming/operators#arithmetic_operators)获得每个数字。 将数字除以 10 所得的余数是该数字的最后一位。 我们使用指数运算符获取多维数据集。 最后,我们将总和与原始数字进行比较,得出结论,如果它们相等,则为阿姆斯特朗数字。 ## 源代码:检查 n 位阿姆斯特朗数 ```py 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`的值,然后再次运行以对其进行测试。