C语言:阶乘的递归与非递归算法

//递归和非递归分别实现求n的阶乘
#include<stdio.h>
#include<stdlib.h>
//非递归
//int test(int x)
//{
// int i = 0;
// int sum = 1;
//
// for (i = 1; i <= x; i++)
// {
//
//  sum=sum*i;
//  
// }
// return sum;
//}
//递归
int test(int x)
{
 if (x == 1)
 {
  return 1;
 }
 else
  return x*test ((x - 1));
}
int main()
{
 int n = 5;

 printf("%d",test(n));
 system("pause");
 return 0;
}

一定要注意递归的约束条件

猜你喜欢

转载自blog.csdn.net/qq_43647265/article/details/86493827
今日推荐