在Java中计算阶乘并打印步骤

时间:2014-03-10 06:20:56

标签: java

以下Java代码计算给定数字的阶乘,并打印中间步骤。

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

调用方法时:

Factorial.getFactorial(4);

应该向控制台打印如下内容:

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

但它打印的内容如下:

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

我做错了什么?

1 个答案:

答案 0 :(得分:3)

这种情况正在发生,因为您只打印factorial变量。替换:

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

使用:

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