【问题标题】:Need help understanding recursion需要帮助理解递归
【发布时间】:2016-10-19 09:23:05
【问题描述】:

所以在我的class 中,我们正在研究递归函数。但我就是不明白它们是如何工作的。

我将以这段代码为例。

// n is written to the screen vertically
// with each digit on a separate line.

void write_vertical(int n) {

    if (n < 10) 
    {
        cout << n << endl;
    }
    else   // n is two or more digits long
    { 
        write_vertical(n/10);
        cout << (n % 10) << endl;
    }
}

所以如果 int n = 123; 它将在自己的行上打印每个数字。这是怎么发生的?这个函数是如何一步步工作的?

【问题讨论】:

  • 尝试手写(评估数学函数)看看发生了什么。
  • 铅笔和纸;),将有助于解决这个问题。通过给它随机 n 个数字来测试它
  • 您的调试器有一个功能可以让您单步执行程序。使用它!
  • 我多次尝试支持@LightnessRacesinOrbit 的评论并破坏了一些东西。
  • 递归已经在this question中解释过了。

标签: c++ recursion


【解决方案1】:

随机数测试(13)

我们以 13 为例。好吧它不小于 10,所以它会执行else 块,它会立即执行函数本身 13/10,(作为整数)是 1。现在 1 小于 10,所以它会打印1 因为endl 而在屏幕上换了一行。现在它将返回到之前的函数调用(在使用参数 1 再次调用函数之前)并执行13%10。 13 模数 10 为 3,因为它的余数变为 3,并带有一个新行(同样是因为 endl)。瞧,你把数字打印在一条垂直线上!

为了未来

您应该使用铅笔和纸,像我们上面那样手动调试它。 或更好地使用像 GDB 这样的调试器! This 是关于如何使用 GDB 进行调试的出色快速入门。

【讨论】:

    【解决方案2】:

    递归很简单。假设您已经编写了函数;然后使用它。

    这里的情况正好相反——你试图弄清楚函数的作用。同样,当你调用它时,它总是做同样的事情。

    那么,在一个数字n &gt; 10 的一般情况下,n/10 是什么(整数除法)?就是那个没有最后一位小数的数字。

    n % 10 是什么?这是数字的最后一位十进制数字。

    所以,你的定义是:

    doing_something for a number `n` IS
    
        doing_it for this number without its last decimal digit 
                             (if there's something left, that is);
    
        then printing its last decimal digit and a newline after it.
    

    就是这样。

    【讨论】:

      【解决方案3】:

      1:

      if(123 < 10)     // fails
          cout << 123; // skipped
      else
      {
          recurse(123 / 10); // recurse(12) converted to int
          cout << 123 % 10; // i'll be back here wait
      }
      

      2:

      if(12 < 10)     // fails
          cout << 12; // skipped
      else
      {
          recurse(12 / 10); // recurse(1)
          cout << 12 % 10; // wiat I'll be back
      }
      

      3:

      if(1 < 10)      // succeeds! so now else executed
          cout << 1; // printed 
      

      在函数返回之前,下面什么都没有,所以我们返回 到 2:

      cout << 12% 10; // (12 % 10 = 2) was wating it's its time
      

      继续下面:下面什么都没有,所以从函数 2 返回到 1:

      在 1 中:

      cout << 123 % 10; // it was waiting so now it's its time
      cout << 123 % 10; // 123 % 10 = 3
      

      往下看:直到函数结束才返回主函数 第一次调用函数的位置(调用后的行)

      结果:1​​23

      【讨论】:

        猜你喜欢
        • 2020-07-04
        • 2016-11-15
        • 2021-11-29
        • 2021-12-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-03
        • 1970-01-01
        相关资源
        最近更新 更多