递归函数

发布于 2024-10-08 05:26:21 字数 421 浏览 2 评论 0原文

给定以下递归函数:

// 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

千寻… 2024-10-15 05:26:21
mysterious(3, 2)

= 2 * mysterious(3, 1)
= 2 * 2 * mysterious(3, 0)
= 2 * 2 * 3
= 12
mysterious(3, 2)

= 2 * mysterious(3, 1)
= 2 * 2 * mysterious(3, 0)
= 2 * 2 * 3
= 12
深巷少女 2024-10-15 05:26:21

如果你扩展该调用,实际上

(2*(2*(3))) == 12

Y 只会减少(每次调用减少 1),因此该函数显然是递归的,并且应该在 y>=0 时终止

if you expand that call you effectively have

(2*(2*(3))) == 12

Y only ever decreases (by 1 each call) so the function is clearly recursive and should terminate for y>=0

贪恋 2024-10-15 05:26:21

每次调用 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)

难得心□动 2024-10-15 05:26:21
mysterious(3, 2)
    y(==2) is not 0 therefore it 
    returns 2 * mysterious(3, 1)
        mysterious(3,1)
            y(==1) is not 0 so it 
            returns 2 * mysterious(3 , 0)
                mysterious(3 , 0) 
                    return 3 because y == 0
            2 * 3 = 6
    2 * 6 = 12

x 永远不会被修改,但是随着每次递归调用,y 都会减一,并且当到达 ground 子句时(if y == 0)它返回 x(第一次调用时为 3)

mysterious(3, 2)
    y(==2) is not 0 therefore it 
    returns 2 * mysterious(3, 1)
        mysterious(3,1)
            y(==1) is not 0 so it 
            returns 2 * mysterious(3 , 0)
                mysterious(3 , 0) 
                    return 3 because y == 0
            2 * 3 = 6
    2 * 6 = 12

x is never modified, but with each recursive call y is reduced by one and when reaches the ground clause (if y == 0) it returns x (which from the first call is 3)

掌心的温暖 2024-10-15 05:26:21

它只不过是

x * 2**y

or

mysterious(x, y) == x*pow(2, y)

,所以它可以很好地定义为 y 的任何值

It's nothing else than

x * 2**y

or

mysterious(x, y) == x*pow(2, y)

so it could be very well defined for any value of y

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文