请用c语言编写求水仙花数的代码
时间: 2024-06-10 16:06:44 浏览: 8
当然,我可以用 C 语言编写求水仙花数的代码。代码如下:
```c
#include <stdio.h>
#include <math.h>
int main()
{
int num, temp, sum = 0, digits = 0;
printf("请输入一个三位数:");
scanf("%d", &num);
temp = num;
// 计算数字位数
while (temp > 0) {
digits++;
temp /= 10;
}
temp = num;
// 计算每个数字的掌数和
while (temp > 0) {
sum += pow(temp % 10, digits);
temp /= 10;
}
if (sum == num) {
printf("%d 是水仙花数\n", num);
} else {
printf("%d 不是水仙花数\n", num);
}
return 0;
}
```
如果输入的数是水仙花数(例如 153),那么输出如下:
```
请输入一个三位数:153
153 是水仙花数
```
如果输入的数不是水仙花数(例如 234),那么输出如下:
```
请输入一个三位数:234
234 不是水仙花数
```
相关问题
C语言程序设计水仙花数代码
以下是两种C语言编写的水仙花数代码示例:
1. 使用循环和数学库函数pow()计算水仙花数:
```c
#include <stdio.h>
#include <math.h>
int main() {
int num, i, sum, j;
printf("100到1000的水仙花数有:\n");
for (num = 100; num <= 1000; num++) {
sum = 0;
j = num;
while (j != 0) {
i = j % 10;
sum += pow(i, 3); // 使用math.h库中的pow()函数来计算一个数字的n次方
j /= 10;
}
if (sum == num) {
printf("%d ", num);
}
}
printf("\n");
return 0;
}
```
2. 使用循环和条件判断计算水仙花数:
```c
#include <stdio.h>
int main() {
int x, y, z, m;
printf("水仙花数 :\n");
for (m = 100; m < 1000; m++) {
x = m / 100;
y = (m / 10) % 10;
z = m % 10;
if (m == x * x * x + y * y * y + z * z * z) {
printf("%6d", m);
}
}
printf("\n");
return 0;
}
```
c语言n位水仙花数代码
以下是用C语言编写的n位水仙花数代码示例:
```c
#include <stdio.h>
#include <math.h>
int main() {
int n, i, sum, j;
printf("请输入位数n:");
scanf("%d", &n);
printf("%d位水仙花数有:\n", n);
for (i = pow(10, n - 1); i < pow(10, n); i++) {
sum = 0;
j = i;
while (j != 0) {
sum += pow(j % 10, n);
j /= 10;
}
if (sum == i) {
printf("%d ", i);
}
}
printf("\n");
return 0;
}
```
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)