2

我不明白这段代码有人可以帮助我吗?我想知道为什么 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);
    }
  }
}
4

4 回答 4

6

这是发生了什么:

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

请注意5 * 4 * 3 * 2 = 120,这是打印的数字。

于 2013-11-12T18:20:54.493 回答
2

展开调用:

fact(5)
5 * fact(5-1)
5 * fact(4)
5 * 4 * fact(4-1)
5 * 4 * fact(3)
5 * 4 * 3 * fact(3-1)
5 * 4 * 3 * fact(2)
5 * 4 * 3 * 2 * fact(2-1)
5 * 4 * 3 * 2 * fact(1)
5 * 4 * 3 * 2 * 1302
120 * 1302
于 2013-11-12T18:21:09.233 回答
2
n = 5
Return 5 * fact(4)
n = 4 
return 4 * fact(3)
n= 3 
return 3* fact(2)  
n = 2 
return 2 * fact(1) 
n = 1
return 1302

现在展开堆栈

n = 2 
return 2 * 1302 (2604)
n= 3 
return 3* 2604 (5208)

... 等等。

于 2013-11-12T18:21:44.583 回答
1
fact(5);
     5 * fact(4);
fact(4);
     4 * fact(3);
fact(3);
     3 * fact(2);
fact(2);
     2 * fact(1);
fact(1);
     1302

所以5 * 4 * 3 * 2 * 1302

于 2013-11-12T18:22:28.973 回答