[英]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;
它会在自己的行上打印每个数字。这是怎么发生的? 此功能如何逐步工作?
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.