【问题标题】:Recursion Check递归检查
【发布时间】:2013-11-13 02:25:50
【问题描述】:

我看不懂这段代码,谁能帮帮我? 我想知道为什么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);
    }
  }
}

【问题讨论】:

  • 为什么在基本情况下返回 1302 而不是 1
  • 我只是在试验这段代码.. 但有人知道为什么会这样吗?
  • @HassaanHafeez 请转到上面提供的链接。我已经回答过了。
  • @HassaanHafeez 因为你递归地调用fact(n-1),所以它会在某个时候到达n = 1。如果您致电fact(3),它将执行=> 3 * fact(2)fact(2) = 2 * fact(1)fact(1) = 1302(在您的情况下)所以fact(3) = 3 * 2 * 1302

标签: java recursion instance


【解决方案1】:

这是怎么回事:

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,这是打印出来的数字。

【讨论】:

  • 啊,我明白了,现在有道理了!谢谢。
  • 4 个相同的答案。但这是格式最好的,也是最容易阅读的。
【解决方案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

【讨论】:

    【解决方案3】:
    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)
    

    ... 等等。

    【讨论】:

      【解决方案4】:
      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

      【讨论】:

        猜你喜欢
        • 2016-12-29
        • 2021-12-27
        • 2021-12-23
        • 1970-01-01
        • 1970-01-01
        • 2017-01-15
        • 2012-03-30
        • 2013-01-22
        • 2013-11-30
        相关资源
        最近更新 更多