需要帮助理解递归

Need help understanding recursion

本文关键字:递归 助理 帮助      更新时间:2023-10-16

在我的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;,它将在自己的行上打印每个数字。这是怎么发生的?这个函数是如何一步步工作的?

随机数(13)检验

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

为未来的<<h2>/h2>

您应该使用铅笔和纸,并像上面所做的那样手动调试它。最好使用像GDB这样的调试器!这个是一个关于如何调试GDB的优秀快速入门。

递归很简单。假设你已经写好了函数;那就用它。

这里是另一种方式-你试图弄清楚函数的作用。同样的,当你调用它时,它总是做同样的事情。

那么,在数字n > 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.

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

go below: nothing直到函数结束,所以返回main函数第一次被调用的地方(调用后的行)