C++ 递归期末考试复习

标签 c++ recursion data-structures recursive-datastructures

在准备即将到来的期末考试时,我遇到了这个复习题,当我调用 test_b(4) 时,我知道答案是:0 2 4。我的问题是为什么它在 0 之后打印 24 如果第一个 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/

相关文章:

javascript - 如何使用递归转置 m*n 矩阵?

c++ - boost::intrusive::list with the auto-unlink hook:我可以使用列表中的值来确定列表是否只有一个元素吗?

c++ - 内存屏障到底要解决什么问题?

c++ - 如何在mongoose服务器c++中获取域名

php - 对象的递归遍历

algorithm - 在具有内存约束的 2 个单链表中有效地搜索公共(public)节点?

c++ - 如何向 C++ 日志宏添加额外参数

loops - 在 Clojure 中退出循环

c# - 基于子项或父项的树结构

c - 给定宽度和长度的矩形的包装