简体   繁体   中英

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. 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. 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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