Java 为什么这个递归方法被认为是阶乘?
直到Java 为什么这个递归方法被认为是阶乘?,java,recursion,Java,Recursion,直到m=1和n=1之前,我都理解这种方法所做的一切。当m=1和n=1时,if()之后发生的事情是有问题的 public class exc { public static void main(String[] args) { System.out.println(prod(1, 4)); } public static int prod(int m, int n) { if (m == n) { return
m=1
和n=1
之前,我都理解这种方法所做的一切。当m=1
和n=1
时,if()
之后发生的事情是有问题的
public class exc {
public static void main(String[] args) {
System.out.println(prod(1, 4));
}
public static int prod(int m, int n) {
if (m == n) {
return n;
} else {
int recurse = prod(m, n - 1);
int result = n * recurse; // how n gets its value here?
return result;
}
}
}
我还在不同的行之后使用println来查看输出,但这也没有帮助。我还使用了调试器。当m=1时,程序返回阶乘。 举个例子:(m=1,n=4)
每次递归调用函数prod时,当前函数prodA都会暂停(将其变量的值保存在内存中)以执行新函数prodB,直到prodB向prodA返回某些内容为止。然后A继续执行自身(从内存中加载其值)在调试中运行该程序怎么样?它被视为“阶乘”,因为它是。不清楚你在问什么。可能是重复的,让
n
的值小于m
,让乐趣开始吧@progy_rock,这不会持续很长时间,堆栈溢出错误会很快发生。
4 != 1 -> so you call recursively prod(1, 3)
3 != 1 -> so you call recursively prod(1, 2)
2 != 1 -> so you call recursively prod(1, 1)
1 == 1 -> you return 1 to the last call
In this call, recurse = 1 and n = 2 so you return 2 to the upper call
Here, recurse = 2, n = 3, so you return 6 to the upper call
Here, recurse = 6, n = 4, so you return 24 to the upper call
END OF FUNCTION, result is 24 which is 4!