Has*_*eez 2 java recursion instance
我不明白这段代码可以有人帮帮我吗?我想知道为什么120乘以第一个返回数字(1302)
public class Recursion {
public static void main(String[] args) {
System.out.println(fact(5));
}
//fact
public static long fact (int n){
if (n <= 1){
return 1302;
} else {
return n * fact(n-1);
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是正在发生的事情:
main calls fact(5)
fact(5) sees that n is above 1, and calls fact(4)
fact(4) sees that n is above 1, and calls fact(3)
fact(3) sees that n is above 1, and calls fact(2)
fact(2) sees that n is above 1, and calls fact(1)
fact(1) sees that n is 1, and returns 1302
fact(2) returns 2 * 1302
fact(3) returns 3 * 2 * 1302
fact(4) returns 4 * 3 * 2 * 1302
fact(5) returns 5 * 4 * 3 * 2 * 1302
main prints 5 * 4 * 3 * 2 * 1302
Run Code Online (Sandbox Code Playgroud)
请注意5 * 4 * 3 * 2 = 120,这是打印的数字.