简体   繁体   English

Java输出的递归方法

[英]Java output of a recursive method

New to recursion. 递归的新手。 The output of this code is 79 , How is this answer reached? 此代码的输出是79 ,如何获得此答案? When written down I find the base case never being reached. 当写下来时,我发现根本无法达到基本情况。 (-3+4) + (2 * -3) = -5 => (-5+4) + (2 * -5) = -11... Do I have a fundamental misunderstanding of recursion or basic algebra? (-3+4) + (2 * -3) = -5 => (-5+4) + (2 * -5) = -11...我对递归或基本代数有基本的误解吗?

int result = negative(-3);

public int negative(int num)
{
    if(num >= 20)
    {
        return -5;
    }
    else
    {
        return negative(num + 4) + 2 * num;
    }
}

public void print()
{
    System.out.println("The final answer is " +result);
}

Your first case isn't (-3+4) it's negative(-3+4) which is negative(1) + (2 * -3). 您的第一种情况不是(-3+4)而是negative(-3+4) ,它是negative(1) +(2 * -3)。 If you change the first line of negative to 如果您将negative的第一行更改为

System.out.println(num);

You can see how the numbers recursively reach the output you've already given. 您可以看到数字如何递归地到达您已经给出的输出。

Try writing this out yourself: 尝试自己写下来:

If the function is sent a number greater than, or equal to 20, it returns -5 如果函数发送的数字大于或等于20,则返回-5

Otherwise, it returns 2*num + (itself again with num+4) 否则,它返回2 * num +(再次使用num + 4本身)

We get: 我们得到:

(2*-3) + (2*1) + (2*5) + (2*9) + (2*13) + (2*17) + (-5) (2 * -3)+(2 * 1)+(2 * 5)+(2 * 9)+(2 * 13)+(2 * 17)+(-5)

Doing the above, you get 74 这样做,您会得到74

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

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