c中递归函数的输出

时间:2019-12-04 14:56:26

标签: c recursion output

我试图找出一个简单的递归函数的输出,该函数计算c中函数内给定数字的阶乘。我对执行的顺序感到困惑 printfprintf("returning %d\n", val);

我希望此代码的输出为:

called with par = 4
called with par = 3
called with par = 2
called with par = 1
returning 24
24

但是输出是:

called with par = 4
called with par = 3
called with par = 2
called with par = 1
returning 2
returning 6
returning 24

代码:

int factorial(int n);
int main(void)
{

printf("%d",factorial(4));

}


int factorial(int n)
{
    int val;
    if ((n == 0) || (n == 1)) 
    {
        printf("called with par = %d\n", n);
        return 1;
    }

    else 
    {
        printf("called with par = %d\n", n);
        val = n * factorial(n - 1);
        printf("returning %d\n", val);
        return val;
    }
}

1 个答案:

答案 0 :(得分:3)

如果我们以您的factorial(4)为例,它会像这样:

factorial(4)
    print "called with par = 4"
    val = 4 * factorial(3)
        print "called with par = 3"
        val = 3 * factorial(2)
            print "called with par = 2"
            val = 2 * factorial(1)
                print "called with par = 1"
                return 1
            print "returning 2"  // 2 * 1 = 2
            return 2
        print "returning 6"  // 3 * 2 = 6
        return 6
    print "returning 24"  // 4 * 6 = 24
    return 24

每次调用n > 1(不幸的是n < 0)时,将同时打印"called with..." "returning..."