递归:为什么堆栈顶部重复两次

时间:2014-05-21 00:31:39

标签: objective-c recursion

我不明白为什么堆栈的顶部会重复两次。

这是我的代码:

void count(n){
    if (n>0) {
        printf("Count is %i \n",n);
        n=n-1;
        count(n);

    } else {
        printf("Count is %i. Finished. \n",n);

    }
        printf("The count here is %i \n",n); //recursion here
    }


int main(int argc, const char * argv[])
{

    @autoreleasepool {

        count(5);

    }
        return 0;
}

输出结果为:

Count is 5
Count is 4
Count is 3 
Count is 2
Count is 1
Count is 0. Finished.
The count here is 0
The count here is 0
The count here is 1
The count here is 2
The count here is 3
The count here is 4
Program ended with exit code: 0

那么,为什么有两行输出说“这里的数是0”? 不是第一行,通过递归的'第一'时间?

2 个答案:

答案 0 :(得分:4)

从逻辑上考虑您的代码,我想您会看到为什么该行被打印两次。考虑我们达到此语句时的情况:n=n-1;和n当前(在执行此操作之前)等于1.现在n为0并且您调用count(n),递归调用您的函数,因为我认为您可能一直在说。现在,您的count(0)函数调用将在此处显示:

else {
        printf("Count is %i. Finished. \n",n);

    }

因为n不大于0.这是我们输出的地方:Count is 0. Finished. 然后,您的函数下一个语句是:printf("The count here is %i \n",n); //recursion here 这会导致第一个输出:The count here is 0

现在考虑一下会发生什么。您的count(0)调用已完成,并返回到调用它的函数。在这种情况下,请考虑您从哪里调用它。你从被称为count(1)的函数中调用它,但现在在该函数中,是n=n-1;的原因,n是0.

在您的代码之后,在if语句之后,您的程序将立即进入:printf("The count here is %i \n",n); //recursion here

因为n为0,它将再次输出The count here is 0

答案 1 :(得分:2)

您确定要吗:

n=n-1;
count(n);

而不是这个?

count(n-1);

前者将修改后续printf中打印的n的值,而后者仅在递归调用中修改它。