简体   繁体   中英

Why does this recursive method return 400 instead of 404?

Why does the method return 400? The value "x" goes from 5, 15, 45, 135, 405, 404, 403, 402, 401, 400. I'm not sure why. Please explain.

public int go(int x) {
    if(x < 300)
        x = go(x * 3);
    return x - 1;
}

It's going to return different values depending on what you initially called it with. If you initially call it with 5, it will return 400 because once it gets to 135 you're 4 layers deep into the recursive function.

So it does return 404 -- to the caller, which returns 403 to it's caller, which returns 402... until it gets to 400 at which point it is at the first caller, which is the value you're printing.

That's how recursive functions work.

Try printing the result of go(go(go(go(go(405))))) if that wasn't clear, because that's what you effectively have in your example when the recursion is done.

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