计算 n 的阶乘。
方法一:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i, n;
int ret = 1; //保存每次相乘的结果,最终阶乘的结果
scanf("%d", &n);
for (i = 1; i <= n; ++i) //用 for 循环来实现阶乘
{
ret = ret * i;
}
printf("%d\n", ret);
system("pause");
return 0;
}
方法二:
#include <stdio.h>
#include <stdlib.h>
int Factor(int n) //用函数调用来实现阶乘
{
int ret = 1; //保存每次相乘的结果,最终阶乘的结果
for (int i = 1; i <= n; ++i)
{
ret = ret * i;
}
return ret;
}
int main()
{
printf("%d\n", Factor(5)); //调用 Factor 函数实现 5!
system("pause");
return 0;
}
本文介绍了两种使用C语言实现阶乘的方法。一种是通过主函数内的循环结构直接完成计算;另一种则是利用函数调用的方式实现阶乘计算。这两种方法都适用于初学者理解递归和循环的概念。

被折叠的 条评论
为什么被折叠?



