如何通过递归方法计算任意数字的阶乘

问题描述 投票:-3回答:1
 ```    

    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个回答
0
投票

这很麻烦,因为您没有注意基本情况(在此问题中,0是基本情况),请尝试以下方法来计算阶乘:

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

    return n * fact(n-1); 
} 
© www.soinside.com 2019 - 2024. All rights reserved.