How to use a recursive function in the C language to calculate the factorial of n?
Here is an example code using a recursive function in C language to calculate the factorial of n.
#include <stdio.h>
// 声明递归函数
unsigned long long factorial(int n);
int main() {
int n;
printf("请输入一个正整数n:");
scanf("%d", &n);
// 调用递归函数求解阶乘
unsigned long long result = factorial(n);
printf("%d的阶乘为%llu\n", n, result);
return 0;
}
// 定义递归函数
unsigned long long factorial(int n) {
if (n <= 1) {
return 1;
}
return n * factorial(n - 1);
}
In the above code, a recursive function called factorial is used to calculate the factorial of n. The function first checks for the termination condition that if n is less than or equal to 1, it returns 1 to indicate the end of the factorial. Otherwise, it continues to call the recursive function with n-1 as the parameter, multiplying the result with n to get the factorial of n.
In the main function, it first reads a positive integer n input by the user, then calls the recursive function factorial to calculate the factorial of n, and finally displays the result on the screen.