用for迭代出所有水仙花数
时间: 2024-05-02 09:23:21 浏览: 13
好的,我理解了,下面是代码:
```python
# 定义一个函数,判断一个数是否为水仙花数
def isNarcissisticNumber(num):
sum = 0 # 将每一位的数字的立方相加
temp = num
while temp > 0:
digit = temp % 10 # 获取个位数
sum += digit ** 3 # 累加立方
temp //= 10 # 去除个位数
if num == sum:
return True
else:
return False
# 打印所有的水仙花数
for num in range(100, 1000):
if isNarcissisticNumber(num):
print(num, end=' ')
```
输出结果:
```
153 370 371 407
```
以上是用 Python 语言写的代码,用 for 循环迭代出所有三位数的水仙花数。如果您有其他问题,欢迎随时提出。
相关问题
c++迭代法输出水仙花数
水仙花数也被称为阿姆斯特朗数,是指一个 n 位数(n≥3),它的每个位上的数字的 n 次幂之和等于它本身。例如:$1^3 + 5^3 + 3^3 = 153$。
以下是使用迭代法输出水仙花数的 Python 代码示例:
```python
for num in range(100, 1000):
sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10
if num == sum:
print(num)
```
输出结果为:
```
153
370
371
407
```
c++迭代器输出水仙花数
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int start, end;
cout << "请输入起始数:";
cin >> start;
cout << "请输入结束数:";
cin >> end;
for(int i = start; i <= end; i++)
{
int num = i;
int sum = 0;
int count = 0;
while(num > 0)
{
count++;
num /= 10;
}
num = i;
while(num > 0)
{
sum += pow(num % 10, count);
num /= 10;
}
if(sum == i)
cout << i << "是水仙花数" << endl;
}
return 0;
}
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)