需要帮助理解递归
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,因此由于endl
的缘故,它将用新行将1打印到屏幕上。现在,它将返回到之前的函数调用(在再次使用参数1调用函数之前)并执行13%10
。13的模10是3,因为它的余数变成3,有一个新的行(同样是因为endl
)。瞧,你在一条垂直线上打印了数字!
您应该使用铅笔和纸,并像上面所做的那样手动调试它。或最好使用像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函数第一次被调用的地方(调用后的行)
相关文章:
- 通过递归进行因子分解
- 递归函数计算序列中的平方和(并输出过程)
- 使用递归的数组的最小值.这是怎么回事
- 递归列出所有目录中的C++与Python与Ruby的性能
- 递归计数给定目录的文件和所有目录
- 如何在BST的这个简单递归实现中消除警告
- C++:正在检查LinkedList中的回文-递归方法-错误
- 递归模板化函数不能分配给具有常量限定类型"const tt &"的变量"state"
- 递归无序映射
- TSP递归解的迭代形式
- 如何在Elixir中调用递归函数并行
- 返回递归调用和仅递归调用的区别
- 数组元素打印的递归方法
- 使用递归时获取变量的奇怪值
- 如何在C++中递归地按相反顺序打印集合
- 到连接组件算法的问题(递归)
- 如何使用递归打印修改后的星号三角形图案
- 使用递归模板动态分配的多维数组
- 递归函数有效,但无法记忆
- 包含模板文件的递归会导致编译失败