【问题标题】:How to calculate the factorial of any number through recursion method如何通过递归方法计算任意数的阶乘
【发布时间】:2020-02-10 09:17:40
【问题描述】:

我通过递归方法对此进行编码。此代码正在计算任何数字的阶乘。我运行此代码及其创建异常。我有任何逻辑错误。我该如何纠正这个问题?

package factorial;

public class Factorial {

    int i=1; 

    public int fact(int f){
        return i*fact(f-1);
    }

    public static void main(String[] args) {
        Factorial fa=new Factorial();
        fa.fact(5);
        System.out.println(fa.i);
    }

}

【问题讨论】:

    标签: java recursion data-structures factorial


    【解决方案1】:
    package factorial;
    
    public class Factorial {
    
        public int fact(int f){
            if(f == 0)
               return 1;
            return f * fact(f-1);
        }
    
        public static void main(String[] args) {
            Factorial fa=new Factorial();
            int factorial = fa.fact(5);
            System.out.println(factorial);
        }
    
    }
    

    【讨论】:

      【解决方案2】:

      你错过了这个问题的基本情况(情况0),请尝试以下方法计算阶乘:

      static int fact(int n) 
      { 
          if (n == 0) 
            return 1; 
      
          return n * fact(n-1); 
      } 
      

      【讨论】:

      • 如果您解释为什么 OP 的代码会引发异常(无限递归),然后解释您的代码如何避免该问题,这将是一个更好的答案。
      • 感谢@JimMischel,编辑了它的解释。
      猜你喜欢
      • 2015-04-19
      • 1970-01-01
      • 2015-01-08
      • 2017-04-19
      • 2013-09-18
      • 1970-01-01
      • 2014-10-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多