递归为什么我在递归java方法中得到“线程中的异常”main“java.lang.StackOverflowerr”?
我试图得到一个输出,使我输入的数字加倍。 在我的示例中,我输入5,并希望输出为10、8、6、4、2。但是我有一个错误,说
Exception in thread "main" java.lang.StackOverflowError
at HelloWorld.recursion(HelloWorld.java:13)
at HelloWorld.recursion(HelloWorld.java:13)
at HelloWorld.recursion(HelloWorld.java:13)
at HelloWorld.recursion(HelloWorld.java:13)
然而,我看到过类似于我的代码,他们都理解正确,我做错了什么?为什么第13行错了
public class HelloWorld{
public static void main(String []args){
System.out.println(recursion(5));
}
public static int recursion(int x){
int temp = x--;
if(x == 0){
return 0;
}
else if(x > 0){
return recursion(temp) + x*2;
}
return -1;
}
}
# 1 楼答案
您正在使用后减量为
int temp
赋值:int temp = x--;
与int temp = x; x--;
相同,因此第13行中recursion
的参数与前面的函数调用相同。结果,你的recursion
函数进入了一个无限循环要使其工作,请改用预减量,即:
将
int temp = x--;
更改为int temp = --x;
,这相当于--x; int temp = x;
。现在recursion(temp)
中的参数递减1# 2 楼答案
将
int temp = x--;
更改为int temp = --x;
,否则,您的递归是无限的# 3 楼答案
调用函数时,它的数据(如参数和局部变量)被放入所谓的函数调用堆栈中。这个堆栈的空间有限,所以如果递归没有停止,就会出现所谓的堆栈溢出。至于代码,其他人已经指出了问题所在。没有为temp指定您认为的值。我建议在递归函数中添加一个print语句,以查看x的实际值。例如,如果每次都传入相同的值,那么递归实际上没有取得任何进展,将达到堆栈大小限制。希望这能帮助你在将来缩小类似的问题。调试愉快
# 4 楼答案
当调用递归(5)时,让我们浏览一下每一行
正如上面其他人提到的,您正在使用后减量,而您可能需要预减量
# 5 楼答案