递归新手。这段代码的输出是79
,这个答案是如何得出的呢?当写下来时,我发现基本情况从未达到。 (-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);
}
最佳答案
您的第一个案例不是(-3+4)
,而是阴性(-3+4)
,即阴性(1)
+ (2 * -3)。如果将第一行负数
更改为
System.out.println(num);
您可以看到数字如何递归地达到您已经给出的输出。
关于递归方法的 Java 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26749231/