c 语言实现 n 的阶乘:定义 factorial 函数,递归计算 n 的阶乘:如果 n 为 0,返回 1。否则,返回 n 乘以 n-1 的阶乘。在 main 函数中:获取要计算阶乘的数字 n。调用 factorial 函数计算 n 的阶乘并打印结果。

n 的阶乘的 C 语言实现
n 的阶乘,记为 n!,表示 1 到 n 的所有自然数的乘积。例如,5! = 1 × 2 × 3 × 4 × 5 = 120。
实现方法:
#include <stdio.h>
int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
int main() {
int n;
printf("请输入数字 n:");
scanf("%d", &n);
printf("n 的阶乘是:%dn", factorial(n));
return 0;
}</stdio.h>
登录后复制
详细说明:
-
factorial 函数:
- 该函数递归地计算 n 的阶乘。
- 如果 n 为 0,它返回 1,因为 0! 定义为 1。
- 否则,它将 n 乘以 n-1 的阶乘,并继续递归计算,直到 n 为 0。
-
main 函数:
- 从用户获取要计算阶乘的数字 n。
- 调用 factorial 函数计算 n 的阶乘,并将其存储在变量中。
- 打印 n 的阶乘。
以上就是n的阶乘c语言怎么写的详细内容,更多请关注叮当号网其它相关文章!
文章来自互联网,只做分享使用。发布者:木子,转转请注明出处:https://www.dingdanghao.com/article/539444.html
