函数递归与迭代

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

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;
}


posted on 2017-05-05 20:43  blfbuaa  阅读(188)  评论(0编辑  收藏  举报