gpt4 book ai didi

java - 使用 Return 语句解析堆栈

转载 作者:行者123 更新时间:2023-11-30 05:51:47 26 4
gpt4 key购买 nike

虽然我认为我对解析 void 方法中的堆栈有深入的了解,但返回方法确实扰乱了我对堆栈的理解。下面的方法特别让我困惑,因为我原以为它会返回 0,但实际上返回了 12。

public static int mystery(int n) { // where the method call is mystery(7)
n--; // since n is decremented before the first
// recursive method, the first stack is method(6)

if(n > 0) // base case
mystery(n);

return n * 2; // 0 * 2 = 0?
}

我的问题是,如果 0 是最后一个进入堆栈的值,为什么该方法在 Mystery(7) 时输出 12。这个方法不还是遵循 LIFO 吗?

最佳答案

这必须是这样的:

public static int mystery(int n) { // where the method call is mystery(7)

n--; // since n is decremented before the first
// recursive method, the first stack is method(6)

if(n > 0) // base case
n = mystery(n);

return n * 2; // 0 * 2 = 0?
}

现在它将始终返回 0。

关于java - 使用 Return 语句解析堆栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53772891/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com