Chinaunix首页 | 论坛 | 博客
  • 博客访问: 398098
  • 博文数量: 41
  • 博客积分: 696
  • 博客等级: 上士
  • 技术积分: 727
  • 用 户 组: 普通用户
  • 注册时间: 2012-03-04 20:41
文章分类

全部博文(41)

文章存档

2012年(41)

分类:

2012-03-16 09:16:03

原文地址:递归与循环 作者:hml1006

  递归就是直接或间接调用自身的算法,把一个的大问题分解成同类的小问题。
  下面是一个阶乘的递归实现。

点击(此处)折叠或打开

  1. #include <stdio.h>

  2. int fact(int n)
  3. {
  4.     if(n < 0){
  5.         printf("the number must be larger than 0\n");
  6.         return -1;
  7.     }
  8.     return n <= 1 ? 1:n*fact(n-1);   //n = 1是递归结束条件
  9. }

  10. int main()
  11. {
  12.     int n = 0;
  13.     int total;
  14.     printf("Please input the number:");
  15.     scanf("%d",&n);
  16.     total = fact(n);
  17.     printf("total = %d\n",total);
  18.     return 0;
  19. }
    递归很容易实现,但是递归的缺点也不小。因为函数调用次数非常多,所以开销很大,效率低。而且,因为给函数传递的参数要压栈,函数本身的局部变量也要放入栈,所以,如果递归层次太深,很容易造成栈溢出。
    下面是循环实现,循环不像递归有那么大的函数调用开销,也不用担心栈溢出,注重效率的地方最好用循环代替递归。

点击(此处)折叠或打开

  1. int main()
  2. {
  3.     int n = 0;
  4.     int total = 1;
  5.     printf("Please input the number:");
  6.     scanf("%d",&n);
  7.     if(n < 0){
  8.         printf("the number must be larger than 0\n");
  9.         return -1;
  10.     }
  11.     for(; n >= 0; n--){
  12.         if(n == 0)
  13.             break;
  14.         total *=n;
  15.     }
  16.     printf("total = %d\n",total);
  17. }

阅读(880) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~