繁体   English   中英

需要帮助了解递归

[英]Need help understanding recursion

因此,在我的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,因此将1打印到由于endl ,屏幕换行了。 现在,它将返回到之前调用的函数(在再次使用参数1调用该函数之前)并执行13%10 13模数10为3,因为它的余数变为3,并且换行了(同样由于endl )。 瞧,您将数字垂直打印了!

为了未来

您应该使用铅笔和纸,然后像上面一样手动进行调试。 甚至更好的使用像一个调试器GDB 是关于如何使用GDB进行调试的极好的快速入门。

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

转到下面:在函数结束之前什么都没有,所以重新运行到第一次调用该函数的main(到调用之后的行)

结果:123

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

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

因此,在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.

就这样。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM