题目:12.【C语言】递归和非递归分别求n的阶乘
C语言实现代码如下:
#include<stdio.h>
int factorial(int n)
{
if (n <= 1)
return 1;
else
return n*factorial(n - 1);
}
int main()
{
int n = 0;
scanf("%d", &n);
printf("%d", factorial(n));
return 0;
}
运行结果如图:
非递归方式:循环方式:从1乘到n即可
#include<stdio.h>
int main()
{
int n = 0;
int factorial = 1;
scanf("%d", &n);
int i = 0;
for (i = 1; i <= n; i++)
{
factorial *= i;
}
printf("%d", factorial);
return 0;
}
运行结果如图: