[C ++在递归函数中递增

问题描述 投票:0回答:2

我在查找递归函数样本时使用grepper找到了此代码片段。我了解翻新部分,该函数如何调用自身-1,直到到达基本情况为止,但是,我不了解else中的最后一行。只是想让我的头在最后一行如何获取要返回的数字,直到它回到起始值。代码中也没有将它设置为+1,因为它向上备份是调用函数本身还是只是我不知道的规则?只是想把我的头放在逻辑上。

void PrintTest(int test)
{
    if (test < 1)
    {
        return; // Exit condition, known as "base case"
    }
    else
    {
        cout << test << " ";
        PrintTest(test-1);
        cout << test << " ";
    }
}

int main()
{
    int a;
    cout << "Enter a number prefarably between 2 and 9: ";
    cin >> a;
    PrintTest(a);

我知道这可能是一个愚蠢的问题,但是只是试图理解为什么“ cout << test <

c++ console-application
2个回答
3
投票

它不是“增加备份数量”。

[递归步骤后,处理从上次中断处继续。因此,您只是看到“下部”堆栈框架完成了处理。

这是事件的顺序,从上到下:

PrintTest(3)        PrintTest(2)         PrintTest(1)         PrintTest(0)
===============================================================================
cout << 3 << " ";
PrintTest(3-1);     cout << 2 << " ";
                    PrintTest(2-1);      cout << 1 << " ";
                                         PrintTest(1-1);      return;
                                         cout << 1 << " ";
                    cout << 2 << " ";
cout << 3 << " ";

3
投票

考虑这个简单的情况:

void foo(int x) {
     std::cout << x << '\n';
     bar(x-1);
     std::cout << x << '\n';
}

我想您可以毫无疑问地预测例如foo(3)的输出:

3
... any output from bar(2) comes here ...
3

现在将bar替换为foo,并为递归添加一个停止符,并且您与PrintTest相同。

© www.soinside.com 2019 - 2024. All rights reserved.