使用for循环从1-20打印出阶乘

时间:2014-10-20 22:28:30

标签: java for-loop

我的程序运行良好,但唯一的问题是数字2的阶乘是2而不是1.它将2的值赋予3,依此类推。因此,输出是一条线,20的阶乘是2,432,902,008,176,640,000。

P.S这不是'家庭作业'它只是编程作为一种爱好。

public class Factorials {

  public static void main(String[] args) {

    int counter;
    long factorials = 1;
    //        long total = 1;

    System.out.printf("%4s%30s\n", "Number", "Factorials");

    for (counter = 1; counter <= 20; factorials *= counter, counter++)
        System.out.printf("%4d%,30d\n", counter, factorials);

  }
}

输出:

Number                    Factorials

   1                              1
   2                              1
   3                              2
   4                              6
   5                             24
   6                            120
   7                            720
   8                          5,040
   9                         40,320
  10                        362,880
  11                      3,628,800
  12                     39,916,800
  13                    479,001,600
  14                  6,227,020,800
  15                 87,178,291,200
  16              1,307,674,368,000
  17             20,922,789,888,000
  18            355,687,428,096,000
  19          6,402,373,705,728,000
  20        121,645,100,408,832,000

请帮帮我:)

2 个答案:

答案 0 :(得分:4)

试试这个,它应该有效:

for(counter = 1; counter <= 20; counter++){
    factorials *= counter;
    System.out.printf("%4d%,30d\n", counter, factorials);

}

更多&#34;干净&#34;(java标准)让for-loop像这样:for(x; x<=y; x++)然后这些{}之间有其他逻辑/计算。

答案 1 :(得分:4)

使用此:

for (counter = 1; counter <= 20;counter++, factorials *= counter) {
    System.out.printf("%4d%,30d\n", counter, factorials);
}

您需要增加counter而不是factorials *= counter。就是这样。

输出

Number                    Factorials
   1                             1
   2                             2
   3                             6
   4                            24
   5                           120
   6                           720
   7                         5,040
   8                        40,320
   9                       362,880
  10                     3,628,800
  11                    39,916,800
  12                   479,001,600
  13                 6,227,020,800
  14                87,178,291,200
  15             1,307,674,368,000
  16            20,922,789,888,000
  17           355,687,428,096,000
  18         6,402,373,705,728,000
  19       121,645,100,408,832,000
  20     2,432,902,008,176,640,000