Java Stack Overflow在递归中使用pre-incrementor



好吧,我做了一个程序,可以找到数谷递归的阶乘。它工作正常,但增量存在问题。看,如果我这样写程序,它不起作用!-

package programming.tutorialnext;
import java.util.Scanner;
public class Factorial_Recursion {
    public static int factorial(int n) {
        if (n == 1) {
            return n;
        } else {
            return n * factorial(n--);
        }
    }
    public static void main(String[] args) {
        Scanner bucky = new Scanner(System.in);
        int n;
        System.out.print("Enter a number for it's factorial :");
        n = bucky.nextInt();
        System.out.print("This is it's factorial : " + factorial(n));
    }
}

它说由于某种原因,即使 no. = 3,堆栈也溢出了!但是,如果我像这样使用预增量器:--n 在顶部,它工作正常!

当然行

不通。 factorial(n--) 具有与 factorial(n) 相同的效果,因为它在递减之前将值传递给递归调用,并且从不使用递减的值,从而导致无休止的递归或至少直到堆栈溢出。

另一方面,当您使用预递增时,递归调用得到 n-1,并且递归有效。

进行这些更改以避免堆栈溢出"

  public static int factorial(int n) {
   int result;
   if (n == 1)
        return 1;
       result = factorial(n-1)*n
       return result }