【问题标题】:Recursions: How recursion works when called twice in a program? [duplicate]递归:在程序中调用两次递归是如何工作的? [复制]
【发布时间】:2017-01-18 15:34:50
【问题描述】:

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

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);
    }

}

请提供输出及其工作原理。

【问题讨论】:

  • 试试看怎么样?

标签: java recursion divide-and-conquer


【解决方案1】:

这个修改可以帮助你理解调用的顺序。 (它只是为你的 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

【讨论】:

    猜你喜欢
    • 2023-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-07
    • 2016-02-20
    • 2016-12-21
    • 1970-01-01
    • 2014-06-22
    相关资源
    最近更新 更多