用c语言(8)编写函数,完成以下功能。函数int issxh(int n)判断整数n是否是水仙花数,若是则返回1,否则返回0。函数int sxh()输出所有的水仙花数,并返回共有多少个水仙花数。main()函数调用sxh()函数输出所有的水仙花数,并输出一共输出了多少个水仙花数
时间: 2024-02-21 18:57:31 浏览: 51
以下是用C语言编写的判断和输出水仙花数的代码:
```c
#include <stdio.h>
#include <math.h>
int issxh(int n) {
int sum = 0, count = 0, digit;
int temp = n;
while (temp > 0) { // 计算n的位数count
count++;
temp /= 10;
}
temp = n;
while (temp > 0) { // 计算n的各位数字的count次方之和sum
digit = temp % 10;
sum += pow(digit, count);
temp /= 10;
}
if (sum == n) { // 如果sum等于n,说明n是水仙花数
return 1;
} else {
return 0;
}
}
int sxh() {
int i, count = 0;
printf("所有的水仙花数是:\n");
for (i = 100; i <= 999; i++) {
if (issxh(i)) { // 如果i是水仙花数,输出它并计数
printf("%d ", i);
count++;
}
}
printf("\n");
return count;
}
int main() {
int count;
count = sxh();
printf("共有%d个水仙花数\n", count);
return 0;
}
```
这个程序定义了两个函数。第一个函数issxh用于判断n是否是水仙花数,它首先计算n的位数count,然后计算n的各位数字的count次方之和sum。如果sum等于n,那么n就是水仙花数,函数返回1;否则,函数返回0。第二个函数sxh用于输出所有的水仙花数,并返回水仙花数的个数。它使用一个for循环遍历100~999之间的每个数,如果这个数是水仙花数,就输出它并计数。最后,在main函数中调用sxh函数,输出所有的水仙花数,并统计它们的个数。