请用C++回答,题目描述 打印出所有"水仙花数",所谓"水仙花数"是指一个三位数,其各位数字立方和等于该本身。 例如:153是一个水仙花数,因为153=1^3+5^3+3^3。 Output: 153 ??? ??? ??? 输入 无 输出 所有的水仙花数,从小的开始。 每行一个
时间: 2023-05-19 21:02:01 浏览: 46
以下是C代码实现:
#include <stdio.h>
int main() {
int i, j, k;
for (i = 1; i <= 9; i++) {
for (j = 0; j <= 9; j++) {
for (k = 0; k <= 9; k++) {
int num = i * 100 + j * 10 + k;
if (num == i * i * i + j * j * j + k * k * k) {
printf("%d\n", num);
}
}
}
}
return 0;
}
输出结果为:
153
370
371
407
每行一个水仙花数,从小到大输出。
相关问题
用c++完成:输出所有的“水仙花数”,水仙花数是指一个三位数,其各位数字立方和等于其本身。
Sure, 我可以很轻松地给您展示如何用C语言输出所有水仙花数:
#include <stdio.h>
#include <math.h>
// 定义函数,用于判断一个数是否是水仙花数
int isArmstrong(int num) {
int temp = num;
int sum = 0;
int n = 0;
while (temp > 0) {
temp /= 10;
n++;
}
temp = num;
while (temp > 0) {
int remainder = temp % 10;
sum += pow(remainder, n);
temp /= 10;
}
return sum == num;
}
int main() {
for (int i = 100; i < 1000; i++) {
if (isArmstrong(i)) {
printf("%d ", i);
}
}
return 0;
}
希望这可以帮到您!
C++l输出所有的"水仙花数",所谓"水仙花数"是指一个3位数,其各位数字立方和等于该数本身。
好的,下面是 C++ 代码实现:
```cpp
#include <iostream>
using namespace std;
// 判断一个数是否是水仙花数
bool isNarcissistic(int num) {
int sum = 0, temp = num;
while (temp) {
int digit = temp % 10;
sum += digit * digit * digit;
temp /= 10;
}
return sum == num;
}
int main() {
for (int i = 100; i <= 999; i++) {
if (isNarcissistic(i)) {
cout << i << " ";
}
}
cout << endl;
return 0;
}
```
运行结果:
```
153 370 371 407
```
相关推荐
![exe](https://img-home.csdnimg.cn/images/20210720083343.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.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)