简体   繁体   English

递归方法打印4次

[英]Recursive Method Prints 4 Times

So I am working on learning how to utilize recursion through Java. 因此,我正在研究如何通过Java使用递归。 I have written a simple program that adds all the numbers between 1 and n and it looks to do it's job. 我编写了一个简单的程序,将1到n之间的所有数字相加,看起来很有效。 Where I get confused is the print statement, it prints 4 times (for each result of each smaller part of the solution) and I am confused how it reaches the print statement if the method is called again and the conditions aren't yet satisfied. 让我感到困惑的是print语句,它打印4次(对于解决方案的每个较小部分的每个结果),并且如果再次调用该方法并且条件还不满足,我将感到困惑,它如何到达print语句。 I understand this can be circumvented by creating an int variable in the main method and having the return be assigned to it. 我知道可以通过在main方法中创建一个int变量并将返回值分配给它来避免这种情况。

public static void main(String[] args) {

    int sum = recursiveCall(5);
}

public static int recursiveCall(int num) {

    int sum = 0;

    if(num == 1) {

        sum = 1;
        System.out.println(sum);
        return sum;
    }
    else {

        sum = recursiveCall(num - 1) + num;
    }

    // Notice it prints out all results of sum, not just the final value.
    System.out.println(sum);

    return sum;
}

Let me explain why this happens. 让我解释一下为什么会这样。

Your second print statement prints all the sum values except for when n = 1. When n = 1 the first print statement will print out the value 您的第二条打印语句将打印所有总和值,但n = 1时除外。当n = 1时,第一条打印语句将打印出该值。

Think about this this way: Every non-void method call will return. 这样考虑:每个非空方法调用都会返回。 If it does not return, it will continue executing until a return statement is reached. 如果不返回,它将继续执行直到到达return语句。

You say that the second print statement should print only the last sum value. 您说第二个打印语句应仅打印最后一个总和值。 But you see, there are only two places that the method can return - in the if (num == 1) statement, or at the end of the method. 但是您会看到,该方法只能返回两个位置-在if (num == 1)语句中或该方法的末尾。 The former location is reached only once when n is 1, which means that the other four times the method will return through the return statement at the end. 前一个位置仅在n为1时到达一次,这意味着该方法的其他四次将在最后通过return语句返回。 To reach the return statement at the end, the second print must be executed. 为了最后到达return语句,必须执行第二次打印。 This means that the second print statement must be executed four times! 这意味着第二个打印语句必须执行四次!

Use a debugger to step through the code step by step. 使用调试器逐步浏览代码。 This is the easiest to understand what actually happens. 这是最容易理解实际发生的情况。

I've drawn a sequence diagram, hope this can explain the recursion procedure. 我已经绘制了序列图,希望它可以解释递归过程。

There is a retrospective procedure for recursion, the next command will be pushed into the call stack before the recursion method is called. 有一个递归的追溯过程,在调用递归方法之前,下一个命令将被推入调用堆栈。 So we can simply say System.out.println will be pushed to call stack before recursiveCall , then after the recursiveCall returned the main process will continue with the top command on the stack, that is System.out.println . 因此,我们可以简单地说System.out.println将在recursiveCall之前推入调用堆栈,然后在recursiveCall返回之后,主进程将继续执行堆栈上的最高命令,即System.out.println

递归过程

It is because of the second print statement below the else. 这是因为else下方的第二个打印语句。 On execution the recursive function is called and it doesn't reach the print statement at the bottom. 在执行时,递归函数将被调用,它不会到达底部的print语句。 But after n=1 ie the if condition is executed then it return to the function recursive(2-1) and go to the down and return sum (also the print) and return the value of sum to the place where recursive(3-1) is called and so on.. . 但是在n = 1即执行if条件之后,它将返回到函数recursive(2-1)并向下并返回sum(也是print),然后将sum的值返回给recursive(3-) 1)被调用等等。 That is where it prints each sum. 那是打印每个金额的地方。

A Code which prints only the final sum is give below.Print is included in the main to print final answer only I hope this will help. 下面给出了仅打印最终金额的代码。主菜单中包含打印仅打印最终答案的代码,希望对您有所帮助。

public class add {

    public static void main(String[] args) {

        int sum = recursiveCall(5);
        System.out.println(sum); // this will print 15
    }

    public static int recursiveCall(int num) {

        int sum = 0;

        if(num == 1) {

            sum = 1;
            //System.out.println(sum); this will print 1
            return sum;
        }
        else {

            sum = recursiveCall(num - 1) + num;
        }
        // System.out.println(sum); //this is the reason for each sum.
        return sum;

    }

}

When the recursion is stack is full, then it starts emptying itself from the tail. 当递归堆栈已满时,它将开始从尾部清空自身。 This is the reason your print statement below the if statements starts to get executed. 这就是您的if语句下面的print语句开始执行的原因。 Note: Recursion process will return its value where its called, so if conditions arent satisfied so it will return to that point, but the whole recursion process will keep on continuing until the stack is emptied. 注意:递归过程将在其调用的地方返回其值,因此,如果不满足条件,它将返回到该点,但是整个递归过程将继续进行直到堆栈被清空。 Whatever i said is what is called the Tail Recursion. 我所说的就是所谓的尾递归。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM