python水仙花数判断程序
时间: 2023-06-13 11:06:16 浏览: 82
以下是判断一个数是否为水仙花数的 Python 程序:
```python
num = int(input("请输入一个三位数:"))
sum = 0
n = num
while n > 0:
digit = n % 10
sum += digit ** 3
n //= 10
if num == sum:
print(num, "是水仙花数")
else:
print(num, "不是水仙花数")
```
程序中,首先要输入一个三位数,然后将这个数的每位数字的立方相加,如果和等于原来的数,那么就是水仙花数,否则不是。
相关问题
python3水仙花数程序
当一个三位数的各个位上数字的立方和正好等于该数本身,则称这个数为水仙花数。例如:153=1^3+5^3+3^3,因此153就是一个水仙花数。
以下是Python3语言的水仙花数程序代码:
```python
for num in range(100, 1000):
# 每个位数上的数字
digit_1 = num // 100
digit_2 = num // 10 % 10
digit_3 = num % 10
# 判断是否为水仙花数
if num == digit_1 ** 3 + digit_2 ** 3 + digit_3 ** 3:
print(num)
```
这段代码会输出100到999之间的所有水仙花数。
Python 水仙花数
Python中的水仙花数是指一个n位数,它的每个位上的数字的n次幂之和等于它本身。例如,153是一个水仙花数,因为1^3 + 5^3 + 3^3 = 153。
以下是一个Python程序来判断一个数是否为水仙花数:
```python
def is_armstrong_number(num):
# 将数字转换为字符串,以便逐位计算
str_num = str(num)
# 获取数字的位数
n = len(str_num)
# 计算每个位上的数字的n次幂之和
sum_of_powers = sum(int(digit) ** n for digit in str_num)
# 判断是否为水仙花数
if sum_of_powers == num:
return True
else:
return False
# 测试是否为水仙花数
num = 153
if is_armstrong_number(num):
print(num, "是水仙花数")
else:
print(num, "不是水仙花数")
```
相关推荐
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)