简体   繁体   English

为什么这个递归方法返回 400 而不是 404?

[英]Why does this recursive method return 400 instead of 404?

Why does the method return 400?为什么该方法返回 400? The value "x" goes from 5, 15, 45, 135, 405, 404, 403, 402, 401, 400. I'm not sure why.值“x”来自 5、15、45、135、405、404、403、402、401、400。我不知道为什么。 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.如果您最初用 5 调用它,它将返回 400,因为一旦达到 135,您将深入递归函数的 4 层。

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.所以它确实返回 404 - 给调用者,调用者返回 403,调用者返回 402...直到它达到 400,此时它位于第一个调用者,这是您正在打印的值。

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.如果不清楚,请尝试打印go(go(go(go(go(405)))))结果,因为当递归完成时,这就是示例中有效的结果。

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

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