如何解决我的Java因子程序中的双重打印?

时间:2016-03-18 02:13:50

标签: java

import java.util.*;

public class Factorial {
    public static void main(String[] args) {
        int num;
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number: ");
        num = sc.nextInt();
        int n = num;
        int result = 1;

        while (num != 1) {
            result = result * num;
            num--;
            System.out.println(result);
        }
        System.out.println("The factorial of " + n + " is " + result);
    }
}

enter image description here

我附上了我的代码和输出的图像。我只想不显示我输入结果的内容。

如果我输入数字5,则输出应为;

Enter No: 5
>20
60
120
The factorial of 5 is 120

1 个答案:

答案 0 :(得分:0)

更改result的初始值(以及您的循环条件)。等等,

int n = num;
int result = num;
while (--num != 1) {
    result *= num;
    System.out.println(result);
}
System.out.printf("The factorial of %d is %d%n", n, result);

<强>解释

当您使用result = result*num;初始 result致电1时,您会得到5的不良输出(因为1 * 55)。如果您从5开始并在循环测试中递减,那么您将获得5 * 4

<强>输出

Enter a number: 5
20
60
120
The factorial of 5 is 120