Java 阶乘循环

Java Factorial loop

问题是阶乘值正在更新 while loop 我认为这就是问题所在。这是代码

while (true) {
    System.out.print("Enter a positive integer: ");
    n = sc.nextInt();
    if (n > 0) {
        System.out.print(n + "! = ");
        for (int i = 1; i <= n; i++) {
            factorial = factorial * i;
            for (int j = 1; j <= n; j++) {
                if (j == n) System.out.printf("%d", j);
                else System.out.printf("%d x ", j);
            }
            System.out.println("");
            System.out.println("The factorial of " + n + " is " + factorial);
        }
    } else {
        System.out.println("Invalid input");
        break;
    }
}

好的,所以这是第一个输入为 5 时的问题

The factorial of 5 is: 120

但是在第二个输入上,当我尝试输入例如 4

时,它是这样的

The factorial of 4 is: 2880

即使 4 的阶乘为 24,它也会更高

只需在 else 块后添加 factorial = 1;