好的,我有一个程序:
public class Rec {
public static void main(String[] args) {
test(5);
}
static void test(int n) {
if (n > 0) {
System.out.println(n);
test(n-1);
System.out.println(n);
}
}
它的输出是5,4,3,2,1,1,2,3,4,5。我的问题是,为什么/如何执行第二个println(n)语句?我以为函数调用会完全切断它,而是以让我感到困惑的方式起作用。这不是功课,什么也不是,我真的很难理解递归的工作原理。
最佳答案
完成后,所有方法调用将返回同一位置。
通过有效地链接它们,您可以获得
System.out.println(5)
System.out.println(4)
System.out.println(3)
System.out.println(2)
system.out.println(1)
// If is not true now.
System.out.println(1)
System.out.println(2)
System.out.println(3)
System.out.println(4)
System.out.println(5)
那有意义吗?