How to write a recursive factorial code in the C language?
Here is an example of C language code for calculating factorial using recursion.
#include <stdio.h>
int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
int main() {
int num;
printf("请输入一个整数:");
scanf("%d", &num);
if (num < 0) {
printf("输入的整数必须大于等于0\n");
} else {
int result = factorial(num);
printf("%d的阶乘是%d\n", num, result);
}
return 0;
}
This code defines a factorial function to calculate the factorial of n. In the main function, an integer is first entered, and then the factorial function is called to calculate the factorial value and output the result. If the input integer is less than 0, an error message will be displayed.