我有这个递归阶乘函数:
public class Driver{
public static void main (String args[])
{
System.out.println(factorial(5));
}
private static int factorial(int n)
{
int product;
if (n <= 2){ product = n; return 2;}
else{
product = n * factorial(n-1);
System.out.println("current product =" + product);
System.out.println("product = " + n + " * factorial(" + (n-1) + ")");
}
return product;
}
}
它打印以下内容:
current product =6
product = 3 * factorial(2)
current product =24
product = 4 * factorial(3)
current product =120
product = 5 * factorial(4)
120
我试图弄清楚这里到底发生了什么。我不明白它是如何开始打印 n = 2 的。当前产品 = 6 是从哪里来的?谢谢!