C语言编写函数判断水仙花数
时间: 2024-06-13 11:07:47 浏览: 19
以下是用C语言编写的判断水仙花数的函数:
```c
int isNarcissistic(int num) {
int sum = 0, temp = num, digit = 0;
while (temp > 0) {
digit = temp % 10;
sum += pow(digit, 3);
temp /= 10;
}
if (sum == num) {
return 1;
} else {
return 0;
}
}
```
该函数接受一个整数参数num,返回值为1表示num是水仙花数,返回值为0表示num不是水仙花数。函数内部使用while循环和pow函数计算num的每一位的立方和,最后与num比较判断是否为水仙花数。
相关问题
c语言用函数求水仙花数
以下是使用C语言编写的函数来求水仙花数的示例代码:
```c
#include <stdio.h>
#include <math.h>
int isArmstrong(int num) {
int originalNum, remainder, n = 0, result = 0;
originalNum = num;
// 计算数字的位数
while (originalNum != 0) {
originalNum /= 10;
++n;
}
originalNum = num;
// 计算每位数字的n次幂并求和
while (originalNum != 0) {
remainder = originalNum % 10;
result += pow(remainder, n);
originalNum /= 10;
}
// 判断是否为水仙花数
if (result == num)
return 1;
else
return 0;
}
int main() {
int start, end;
printf("请输入范围: ");
scanf("%d %d", &start, &end);
printf("水仙花数: ");
for (int i = start; i <= end; i++) {
if (isArmstrong(i))
printf("%d ", i);
}
return 0;
}
```
判断水仙花数的函数编写c语言
以下判断水仙花数的函数的C语言代码:
```c
#include <stdio.h>
#include <math.h>
int isArmstrong(int num) {
int sum = 0, temp = num, digitCount = 0;
while (temp > 0) {
temp /= 10;
digitCount++;
}
temp = num;
while (temp > 0) {
int digit = temp % 10;
sum += pow(digit, digitCount);
temp /= 10;
}
return sum == num;
}
int main() {
int num;
printf("请输入一个正整数:");
scanf("%d", &num);
if (isArmstrong(num)) {
printf("%d是水仙花数\n", num);
} else {
printf("%d不是水仙花数\n", num);
}
return 0;
}
```
该函数首先通过两个while循环分别计算num的位数和每一位的数字,然后根据水仙花数的定义计算各位数字的n次方之和,最后将之和与原数比较判断是否为水仙花数。在主函数中,我们通过输入一个数字来调用该函数并输出结果。
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![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_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)