递归和非递归分别实现求n的阶乘
#include<stdio.h>
#include<Windows.h>
int fact(int n)
{
if (n <= 1)
{
return 1;
}
return n*fact(n - 1);
}
int fact2(int n)
{
int res = 1;
while (n>1)
{
res *= n;
n--;
}
return res;
}
int main()
{
int res1 = fact(4);
int res2 = fact2(5);
printf("%d\n", res1);
printf("%d", res2);
system("pause");
return 0;
}
本文探讨了两种不同的方法来计算阶乘:递归和非递归。通过对比,展示了递归方法的简洁性和非递归方法的效率。代码示例使用C语言实现,适用于计算机科学和编程初学者理解递归原理。
764

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



