简体   繁体   中英

Calculating factorials in Java and printing the steps

The following Java code calculates the factorial of a given number and also prints the intermediate steps.

public class Factorial {
   public static int getFactorial(int number) {
     int n = number;
     int factorial = 1;

     while(n > 1) {
       factorial *= n;
       n--;

       System.out.println(factorial + " * " + n + " = " + factorial);
     }

    return factorial;
   }
}

When the method is called:

Factorial.getFactorial(4);

Should print to the console something like the following:

4 * 3 = 12
12 * 2 = 24
24 * 1 = 24

But instead it prints something like the following:

4 * 3 = 4
12 * 2 = 12
24 * 1 = 24

What am I doing wrong?

That is happening because you're printing the factorial variable only. Replace:

System.out.println(factorial + " * " + n + " = " + factorial);

with:

System.out.println(factorial + " * " + n + " = " + factorial * n);

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