递归原理

递归思想
程序调用自身的编程技巧称为递归( recursion)


例如,设计一个程序设计计算n!。

先分析递归的思想,现在要计算6!
分解为6×5!
分解为6×5×4!
分解为6×5×4×3!
...
分解为6×5×4×3×2×1

#include<stdio.h>
int fact(int n)
{
    if(n==1)
        return 1;
    else
        return n*fact(n-1);
}
int main()
{
    printf("%d",fact(3));
    return 0;
}


递归的程序是
int fact(3)
{
    if(n==1)
        return 1;
    else
        return 3*fact(2);
//这里的fact(2)又是一个递归程序

//因为不知道fact(2)的值所以只能继续调用fact(2)
}


int fact(2)
{
    if(n==1)
        return 1;
    else
        return 2*fact(1);
}

int fact(1)
{
    if(n==1)
        return 1;
    else
        return 1*fact(0);
}

当程序运行到fact(1)时候,return 1,回调,所以fact(2) return 2*1,所以fact(3)return3*2*1。最后得到答案

原文地址:https://www.cnblogs.com/handsometaoa/p/11517537.html