递归函数
给定以下递归函数:
// Pre-condition: y is non-negative.
int mysterious(int x, int y) {
if (y == 0) return x;
return 2*mysterious(x, y-1);
}
神秘(3, 2)的返回值是多少?
这是我的调用堆栈:
return 2*mysterious(3, 2-1) => 2*3 => 6, 2*1 => mysterious(6,2)
return 2*mysterious(6, 2-1) => 6*2 => 12, 2*2 => mysterious(12, 2)
但看起来 y 永远不会达到 0。我做错了什么?
Given the following recursive function:
// Pre-condition: y is non-negative.
int mysterious(int x, int y) {
if (y == 0) return x;
return 2*mysterious(x, y-1);
}
What is the return value of mysterious(3, 2)?
Here is my call stack:
return 2*mysterious(3, 2-1) => 2*3 => 6, 2*1 => mysterious(6,2)
return 2*mysterious(6, 2-1) => 6*2 => 12, 2*2 => mysterious(12, 2)
But it seems like y will never reach 0. What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果你扩展该调用,实际上
Y 只会减少(每次调用减少 1),因此该函数显然是递归的,并且应该在
y>=0
时终止if you expand that call you effectively have
Y only ever decreases (by 1 each call) so the function is clearly recursive and should terminate for
y>=0
每次调用 Mystery 时(由您调用一次,通过递归调用两次),y 就会减 1。
因此,您得到(在 Mystery 中)
3 2
3 1
3 0
最终值为12(3*2*2)
Each time mysterious is called (once by you, twice by recursion), y is decremented by 1.
So, you get (in mysterious)
3 2
3 1
3 0
the final value is 12 (3*2*2)
x
永远不会被修改,但是随着每次递归调用,y
都会减一,并且当到达 ground 子句时(if y == 0
)它返回 x(第一次调用时为 3)x
is never modified, but with each recursive cally
is reduced by one and when reaches the ground clause (if y == 0
) it returns x (which from the first call is 3)它只不过是
or
,所以它可以很好地定义为
y
的任何值It's nothing else than
or
so it could be very well defined for any value of
y