【发布时间】: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中解释过了。