简体   繁体   English

递归程序到达return语句,但跳回到方法中的调用

[英]Recursive program reaches return statement, but jumps back to call in method

When I run this program through eclipse's debugger, in the method randomRecursion , once i is less than 0 , it skips to the return, but then jumps back up to the randomRecursion call. 当我通过eclipse的调试器运行该程序时,在randomRecursion方法中,一旦i小于0 ,它就会跳到返回值,然后又跳回到randomRecursion调用。 Why is this? 为什么是这样?

public class RecursiveExample {

    public static double randomRecursion(double a, double b, int i) {
        while (i > 0) { 
            b = ((1 / a) - a) * b;
            i = i - 1;
            randomRecursion(a, b, i);
        }
        return b;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 5; i++)
            System.out.println(randomRecursion(.5, .5, i));
    }
}

Calling the recursive method doesn't terminate your method - you missed the return there. 调用递归方法不会终止您的方法-您错过了那里的return Once you've done that, as @pjs mentioned in the comments, you really have no need for a while loop - you just need a simple conditional statement: 完成此操作后,正如注释中提到的@pjs一样,您实际上不需要while循环-您只需要一个简单的条件语句:

public static double randomRecursion(double a, double b, int i) {
    if (i > 0) { 
        b = ((1 / a) - a) * b;
        i = i - 1;
        // return was missing here
        return RandomRecursion(a, b, i);
    }
    return b;
}

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

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