先看一下代码:
public class Recursion {
public static void main(String[] args) {
System.out.println(factorial(5));
}
private static int factorial(int n) {
if (n <= 1) {
return n;
}
return n + factorial(n--);
}
}
第一眼看上去没有问题,但是运行就会发现一个错误:
发生栈溢出错误,虽然递归会大量消耗栈空间但也不能阶乘求和到5就溢出。
这里的问题其实是n-- 与 --n的不正确使用引起的,这两个的区别不用赘述,之所以这里引起这个错误是因为,递归调用facatorial(n–)时,方法被递归调用后n才做了-1操作,而这个时候新的方法会在栈空间开辟自己的运行空间,而它的栈空间中n是没有-1的,所以实际上每一次的递归操作都没有修改n的值,n始终是5,可以debug查看,也可以简单地在上面程序中factorial方法递归调用之前输出一下n。