编写程序,求水仙花数。所谓水仙花数,是指一个三位数 abc,如果满足 a3+b3+c3=abc, 则 abc 是水仙花数。如 153 是水仙花数,1 3 +53 +33 =153。用C语言
时间: 2024-02-05 15:11:43 浏览: 29
以下是用 C 语言编写的求解水仙花数的程序:
```c
#include <stdio.h>
#include <math.h>
int main()
{
int num, temp, sum = 0;
printf("水仙花数是:");
for(num = 100; num <= 999; num++)
{
temp = num;
while(temp != 0)
{
sum += pow(temp % 10, 3);
temp /= 10;
}
if(sum == num)
{
printf("%d ", num);
}
sum = 0;
}
printf("\n");
return 0;
}
```
程序中使用了一个 for 循环来遍历所有三位数,然后使用一个 while 循环来计算这个三位数的各位数字的立方和。如果计算出的立方和等于这个三位数本身,就说明这个数是水仙花数,将其输出即可。
相关问题
用c语言编写程序,求水仙花数。所谓水仙花数,是指一个三位数abc,如果满足a³+b³+c³=abc,则abe是水仙花数。
好的,这是一个简单的求水仙花数的程序,你可以参考一下:
```c
#include <stdio.h>
int main() {
int a, b, c, num;
for (num = 100; num <= 999; num++) {
a = num / 100;
b = num / 10 % 10;
c = num % 10;
if (num == a * a * a + b * b * b + c * c * c) {
printf("%d ", num);
}
}
return 0;
}
```
这个程序会输出所有的三位水仙花数,结果如下:
```
153 370 371 407
```
其中,153 = 1³ + 5³ + 3³,370 = 3³ + 7³ + 0³,371 = 3³ + 7³ + 1³,407 = 4³ + 0³ + 7³。
求100~999中的水仙花数。若三位数ABC=A3+B3+C3,则称ABC为水仙花数。C++
可以使用三重循环来枚举100~999中的所有三位数,并判断是否为水仙花数。
代码如下:
```c++
#include <iostream>
using namespace std;
int main() {
for (int i = 100; i <= 999; i++) {
int a = i / 100; // 百位数
int b = (i / 10) % 10; // 十位数
int c = i % 10; // 个位数
if (a*a*a + b*b*b + c*c*c == i) {
cout << i << endl;
}
}
return 0;
}
```
输出结果为:
```
153
370
371
407
```
相关推荐
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![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)