这个修改可以帮助你理解调用的顺序。 (它只是为你的 system.out.println() 添加上下文)
public class StackOverflowQuestions {
public static void main(String args[]) {
divide(20, "x=20, depth=0, initial call", 1);
}
public static void divide(int x, String callOrder, int depth) {
System.out.println(callOrder);
if (x > 1) {
divide(x / 2, callOrder+" ; x="+x/2+",depth="+depth+",call=1", depth+1);
divide(x / 4, callOrder+" ; x="+x/4+",depth="+depth+",call=2", depth+1);
}
}
}
这是输出:
x=20, depth=0, initial call
x=20, depth=0, initial call ; x=10,depth=1,call=1
x=20, depth=0, initial call ; x=10,depth=1,call=1 ; x=5,depth=2,call=1
x=20, depth=0, initial call ; x=10,depth=1,call=1 ; x=5,depth=2,call=1 ; x=2,depth=3,call=1
x=20, depth=0, initial call ; x=10,depth=1,call=1 ; x=5,depth=2,call=1 ; x=2,depth=3,call=1 ; x=1,depth=4,call=1
x=20, depth=0, initial call ; x=10,depth=1,call=1 ; x=5,depth=2,call=1 ; x=2,depth=3,call=1 ; x=0,depth=4,call=2
x=20, depth=0, initial call ; x=10,depth=1,call=1 ; x=5,depth=2,call=1 ; x=1,depth=3,call=2
x=20, depth=0, initial call ; x=10,depth=1,call=1 ; x=2,depth=2,call=2
x=20, depth=0, initial call ; x=10,depth=1,call=1 ; x=2,depth=2,call=2 ; x=1,depth=3,call=1
x=20, depth=0, initial call ; x=10,depth=1,call=1 ; x=2,depth=2,call=2 ; x=0,depth=3,call=2
x=20, depth=0, initial call ; x=5,depth=1,call=2
x=20, depth=0, initial call ; x=5,depth=1,call=2 ; x=2,depth=2,call=1
x=20, depth=0, initial call ; x=5,depth=1,call=2 ; x=2,depth=2,call=1 ; x=1,depth=3,call=1
x=20, depth=0, initial call ; x=5,depth=1,call=2 ; x=2,depth=2,call=1 ; x=0,depth=3,call=2
x=20, depth=0, initial call ; x=5,depth=1,call=2 ; x=1,depth=2,call=2
如您所见,始终使用两个方法调用中的第一个,直到满足您的中断条件 x