简体   繁体   English

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

[英]How to resolve double printing in my Java factorial program?

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

在此处输入图片说明

I attached the image of my code and output. 我附加了代码和输出的图像。 I just want to not display what I enter to the result. 我只想不显示输入的结果。

If I entered number 5 the output should be; 如果我输入数字5,则输出应为;

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

Change the initial value of result (and your loop condition). 更改result的初始值(和您的循环条件)。 To something like, 像这样

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

Explanation 说明

When you call result = result*num; 当您调用result = result*num; with an initial result of 1 you get your undesired output of 5 (because 1 * 5 is 5 ). 初始 result1将得到不想要的输出5 (因为1 * 55 )。 If you start with 5 and decrement in the loop test then you'll get 5 * 4 . 如果从5开始并在循环测试中递减,则将得到5 * 4

Output 输出量

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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