Java 递归:在一个程序中调用两次时,递归是如何工作的?

Java 递归:在一个程序中调用两次时,递归是如何工作的?,java,recursion,divide-and-conquer,Java,Recursion,Divide And Conquer,这个程序的输出是什么?它将是怎样的 public class Recursion { static int p=100; public static void main(String args[]) { divide(20); } public static void divide(int x) { System.out.println(x); if(x>1) {

这个程序的输出是什么?它将是怎样的

public class Recursion 
{
    static int p=100;
    public static void main(String args[])
    {
        divide(20);
    }
    public static void divide(int x)
    {
        System.out.println(x);
        if(x>1)
        {
            divide(x/2);
            divide(x/4);
        }
        //System.out.println(x);

    }
    public static void multiply(int x)
    {
        System.out.println("X="+x);
    }

}

请提供输出及其工作状态。

此修改可帮助您了解呼叫顺序。它只是将上下文添加到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

正如您所看到的,您的两个方法调用中的第一个始终被使用,直到您的中断条件为x0为止。试一试怎么样?