c++ 三位水仙花数是指一个三位数,它得每个位上的数字的3次幂之和等于它本身。例如1^3+5^3+3^3=153。编写一个函数,打印所有3位的水仙花数
时间: 2023-12-23 14:04:56 浏览: 34
以下是C语言实现的代码:
```c
#include <stdio.h>
int main() {
int i, j, k, num;
for (i = 1; i <= 9; i++) {
for (j = 0; j <= 9; j++) {
for (k = 0; k <= 9; k++) {
num = i * 100 + j * 10 + k;
if (num == i * i * i + j * j * j + k * k * k) {
printf("%d\n", num);
}
}
}
}
return 0;
}
```
首先使用三重循环遍历所有可能的三位数,然后判断每个数是否为水仙花数,即判断它的每一位数字的3次幂之和是否等于它本身。如果是,就打印出来。
相关问题
判断给定的三位数是否 水仙花 数。所谓 水仙花 数是指其值等于它本身 每位数字立方和的数。例 153 就是一个 水仙花 数。 写出C++代码
以下是C++代码实现:
```c++
#include <iostream>
using namespace std;
int main() {
int num;
cin >> num;
int digit1 = num % 10; // 取个位数
int digit2 = (num / 10) % 10; // 取十位数
int digit3 = num / 100; // 取百位数
if (num == digit1 * digit1 * digit1 + digit2 * digit2 * digit2 + digit3 * digit3 * digit3) {
cout << num << "是水仙花数" << endl;
} else {
cout << num << "不是水仙花数" << endl;
}
return 0;
}
```
程序首先读入一个三位数,然后分别取出它的个位数、十位数和百位数。接着,使用if语句判断这个三位数是否等于它本身每位数字立方和的值,如果是,则输出该数是水仙花数,否则输出该数不是水仙花数。
用C++写出一段代码,计算输出所有三位数中的水仙花数。水仙花数是指一个 n 位数 ( n≥3 ),它的每个位上的数字的 n 次幂之和等于它本身。(例如:13 + 53 + 33 = 153)。
以下是用C++语言编写的计算输出所有三位数中的水仙花数的代码:
```c++
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
for(int i = 100; i < 1000; i++)
{
int sum = pow(i / 100, 3) + pow(i / 10 % 10, 3) + pow(i % 10, 3);
if(sum == i)
{
cout << i << " ";
}
}
return 0;
}
```
代码中,我们使用了 `for` 循环遍历所有三位数。在循环内部,我们使用 `pow()` 函数计算出每个位上的数字的三次幂之和,并将其存储在 `sum` 变量中。如果 `sum` 等于这个三位数本身,就说明这个数是水仙花数,将其输出即可。
相关推荐
![text/plain](https://img-home.csdnimg.cn/images/20210720083646.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)