在准备即将到来的期末考试时,我遇到了这个复习题,当我调用 test_b(4)
时,我知道答案是:0 2 4
。我的问题是为什么它在 0
之后打印 2
和 4
如果第一个 test_b(n - 2)
出现在 cout
之前?
void test_b(int n)
{
if (n>0)
test_b(n-2);
cout << n << " ";
}
最佳答案
考虑 V
形状的调用:
test_b(4)
| //>0, so enter the if
| test_b(2)
| | //>0 so enter the if
| | test_b(0)
| | | //==0, so skip if
| | | print 0 // from the test_b(0)
| | | return
| | print 2 // from test_b(2)
| | return
| print 4 // from test_b(4)
| return
// end
结果如打印所示,首先是 0,然后是 2,最后是 4:0 2 4。
关于C++ 递归期末考试复习,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43895656/