简体   繁体   中英

Java Factorial loop

The problem is that the factorial value is updating in a while loop I think that is the problem why. Here is the code

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;
    }
}

Okay, so here is the problem when the first input is 5

The factorial of 5 is: 120

But on the second input it goes like this when I tried to input like for example 4

The factorial of 4 is: 2880

it goes higher even though the factorial of 4 is 24

Just add factorial = 1; after the else block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM