码迷,mamicode.com
首页 > 其他好文 > 详细

函数递归与迭代

时间:2015-03-12 19:21:14      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:c

递归的缺陷:当执行较多次数的压栈过程会导致运算量过大。但是每一个尾递归都可以写成循环(用一个不土的说法就是迭代)

fabonacii数列用迭代方式实现:

#include<stdio.h>
int Fibonacii(int n)
{
    int temp = 0;
    int a = 1;//记得给头两个数赋初值
    int b = 1;
    if(n <= 2)
        return 1;
    while(n > 2)
    {
        temp = a + b;
        a = b;
        b = temp;//切忌写成 a = temp; b = a;这时的a已经改变!=1再赋给b已经没有意义
        n--;//调整ab中存放的值向前移动
    }
    return temp;
}
int main()
{
    printf("%d\n",Fibonacii(6));
    return 0;
}


用迭代的方式实现阶乘:

#include<stdio.h>
int fac(int n)
{
    int ret = 1;
    while(n)
    {
        ret = ret * n;
        n--;// ret = 1*n,ret = n*(n-1) ....倒着往回乘
    }
    return ret;
}
int main()
{
    printf("%d\n",fac(3));
    return 0;
}


函数递归与迭代

标签:c

原文地址:http://blog.csdn.net/cherry_ermao/article/details/44206121

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!