递归方法打印 4 次 [英] Recursive Method Prints 4 Times

查看:49
本文介绍了递归方法打印 4 次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在学习如何通过 Java 使用递归.我编写了一个简单的程序,它将 1 和 n 之间的所有数字相加,它看起来可以完成它的工作.我感到困惑的是打印语句,它打印 4 次(对于解决方案的每个较小部分的每个结果),如果再次调用该方法并且条件尚未满足,我很困惑它如何到达打印语句.我知道这可以通过在 main 方法中创建一个 int 变量并将返回值分配给它来规避.

So I am working on learning how to utilize recursion through Java. I have written a simple program that adds all the numbers between 1 and n and it looks to do it's job. 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. I understand this can be circumvented by creating an int variable in the main method and having the return be assigned to it.

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

推荐答案

我画了一个时序图,希望能说明递归过程.

I've drawn a sequence diagram, hope this can explain the recursion procedure.

递归有一个追溯过程,下一个命令会在递归方法被调用之前被压入调用栈.所以我们可以简单地说System.out.println会在recursiveCall之前被压入调用栈,然后在recursiveCall返回后主进程会继续使用栈顶命令,即System.out.println.

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.

这篇关于递归方法打印 4 次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆