用python输入水仙花数
时间: 2024-02-28 17:49:22 浏览: 93
以下是用Python判断并输出水仙花数的代码示例:
```python
for i in range(100, 1000):
# 将数字转换为字符串,然后分离出每个数字
num_str = str(i)
a = int(num_str[0])
b = int(num_str[1])
c = int(num_str[2])
# 判断是否为水仙花数
if a**3 + b**3 + c**3 == i:
print(i)
```
这段代码会从100到999遍历所有三位数,将每个数字拆分成百位、十位和个位,并判断是否满足水仙花数的条件。如果满足条件,则打印该数字。
相关问题
python输入水仙花数
水仙花数是指一个三位数,其各位数字立方和等于该数本身。下面是输入水仙花数的 Python 代码:
```python
for num in range(100, 1000):
# 分解出个位、十位、百位
digit1 = num // 100
digit2 = (num // 10) % 10
digit3 = num % 10
# 判断是否为水仙花数
if num == digit1 ** 3 + digit2 ** 3 + digit3 ** 3:
print(num)
```
运行结果为:
```
153
370
371
407
```
用Python判断水仙花数
以下是用 Python 判断水仙花数的代码:
```python
num = int(input("请输入一个数字:"))
sum = 0
n = len(str(num))
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** n
temp //= 10
if num == sum:
print(num, "是水仙花数")
else:
print(num, "不是水仙花数")
```
这段代码可以判断一个数是否为水仙花数,水仙花数是指一个 n 位数 (n≥3),它的每个位上的数字的 n 次幂之和等于它本身。例如,153 是一个水仙花数,因为 1^3 + 5^3 + 3^3 = 153。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.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)
![](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)