1. 递归调用该函数,直到满足条件。那个条件是a > b
。当满足这个条件时,返回0。乍一看,我认为返回值是0,这显然是不正确的。
这是计算机计算的内容sumInts(2,5)
会想如果它能够:
I want to compute sumInts(2, 5)
for this, I need to compute sumInts(3, 5)
and add 2 to the result.
I want to compute sumInts(3, 5)
for this, I need to compute sumInts(4, 5)
and add 3 to the result.
I want to compute sumInts(4, 5)
for this, I need to compute sumInts(5, 5)
and add 4 to the result.
I want to compute sumInts(5, 5)
for this, I need to compute sumInts(6, 5)
and add 5 to the result.
I want to compute sumInts(6, 5)
since 6 > 5, this is zero.
The computation yielded 0, therefore I shall return 5 = 5 + 0.
The computation yielded 5, therefore I shall return 9 = 4 + 5.
The computation yielded 9, therefore I shall return 12 = 3 + 9.
The computation yielded 12, therefore I shall return 14 = 2 + 12.
如您所见,对函数的一些调用sumInts
实际上返回 0,但这不是最终值,因为计算机仍然必须将 5 添加到 0,然后将 4 添加到结果中,然后添加 3,然后添加 2,正如我们计算机思想的最后四个句子所描述的那样。请注意,在递归中,计算机不仅必须计算递归调用,还必须记住如何处理递归调用返回的值。计算机内存中有一个特殊的区域,称为堆栈保存此类信息的空间是有限的,过于递归的函数可能会耗尽堆栈:这就是堆栈溢出以我们最喜爱的网站的名字命名。
你的陈述似乎隐含地假设计算机忘记了在进行递归调用时它所处的位置,但事实并非如此,这就是为什么你的结论与你的观察不符的原因。
2.在每次迭代中打印出“a”的值会产生一个我期望的值:2,3,4,5(此时5+1>b满足第一个条件:a>b)但我仍然没有看到14的值是如何实现的。
这是因为返回值不是a
本身而是值的总和a
以及递归调用返回的值。