【发布时间】:2023-03-16 15:15:01
【问题描述】:
虽然我认为我对在 void 方法中解析堆栈有深入的了解,但 return 方法确实混淆了我对堆栈的理解。以下方法特别让我感到困惑,因为我原以为它会返回 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?
}
我的问题是为什么方法在神秘(7)时输出 12,如果 0 是进入堆栈的最后一个值。这种方法不还是遵循LIFO吗?
【问题讨论】:
-
仔细看。递归调用不影响结果!
(7 - 1) * 2是12 -
由于你的方法从来没有
returns 是递归调用的结果,实际上返回给main的是第一个调用n==2 -
@GBlodgett 更准确地说,该方法确实在递归调用中返回值,但该值从未使用过。第一个电话也是
7。 -
@Jai 但是递归调用从来没有返回语句,那么它如何返回值?
-
@Letta 你在递归调用
mystery(),这个方法返回一个int,所以它肯定会在那里返回一个int。并且每个栈中n的值属于特定栈,没有“通用”n被所有栈共享。