c语言求n!有库函数吗
时间: 2023-06-18 10:07:31 浏览: 65
C语言中可以使用`<stdlib.h>`库中的`factorial`函数来求阶乘,但是事实上这个库函数并不存在,需要自己实现求阶乘的函数。
下面是一个使用递归实现的求阶乘的函数:
```c
#include <stdio.h>
int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
int main() {
int n = 5;
printf("%d! = %d\n", n, factorial(n));
return 0;
}
```
该程序输出:
```
5! = 120
```
上述代码中的`factorial`函数使用递归的方式实现,当输入参数`n`为0时,直接返回1;否则返回`n`乘以`factorial(n - 1)`的结果,即`n`的阶乘。
需要注意的是,当输入的`n`比较大时,递归的深度会变得很大,可能会导致栈溢出,因此需要考虑使用循环等其他方式实现。
相关问题
求字符串长度的库函数c语言
C语言中求字符串长度的库函数是 `strlen()`。
它的函数原型为:
```c
size_t strlen(const char *str);
```
其中,`str` 是指向要求长度的字符串的指针,函数返回值是字符串的长度,类型为 `size_t`。
例如,下面的代码可以计算字符串 `str` 的长度并将其打印出来:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "hello world";
size_t len = strlen(str);
printf("The length of the string is: %zu\n", len);
return 0;
}
```
输出结果为:
```
The length of the string is: 11
```
C语言十六进制转十进制库函数
C语言中可以使用标准库函数 strtol() 将十六进制字符串转换为十进制数。示例代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
int main() {
char hex_string[] = "1A";
char *end_ptr;
long dec_num = strtol(hex_string, &end_ptr, 16);
printf("Hex string %s in decimal is %ld\n", hex_string, dec_num);
return 0;
}
```
输出:
```
Hex string 1A in decimal is 26
```