找出到1000的水仙花数
时间: 2023-10-19 20:39:44 浏览: 40
水仙花数是指一个 n 位数 ( n≥3 ),它的每个位上的数字的 n 次幂之和等于它本身,例如 153,1³ + 5³ + 3³ = 153。
要找到到1000的水仙花数,我们可以用循环来遍历所有三位数,判断每个数是否为水仙花数。具体实现如下:
```c++
#include <iostream>
#include <cmath>
using namespace std;
int main() {
for (int i = 100; i <= 999; i++) {
int sum = 0;
int n = i;
while (n > 0) {
int digit = n % 10;
sum += pow(digit, 3);
n /= 10;
}
if (sum == i) {
cout << i << " ";
}
}
return 0;
}
```
输出结果为:
```
153 370 371 407
```
其中,153, 370, 371, 407 都是三位水仙花数。
相关问题
用python找出100到1000的水仙花数
以下是用 Python 找出100到1000的水仙花数的代码:
```python
for num in range(100, 1001):
# 将数字拆分出每个数位
digits = [int(digit) for digit in str(num)]
# 计算每个数位的立方和
sum_of_cubes = sum([digit**3 for digit in digits])
# 判断是否为水仙花数并输出
if num == sum_of_cubes:
print(num)
```
输出结果为:
```
153
370
371
407
```
用Python找1000水仙花数
好的,水仙花数指的是一个三位数,其各位数字的立方和等于这个数本身。那么,我们可以用 Python 编写一个程序来找出 1000 以内的所有水仙花数。
代码如下:
```python
for i in range(100, 1000):
# 求出 i 的各位数字
a = i // 100
b = i // 10 % 10
c = i % 10
# 判断是否为水仙花数
if a**3 + b**3 + c**3 == i:
print(i)
```
这样,程序就会输出 1000 以内的所有水仙花数。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)