简体   繁体   中英

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;

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

Change the initial value of result (and your loop condition). 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; with an initial result of 1 you get your undesired output of 5 (because 1 * 5 is 5 ). If you start with 5 and decrement in the loop test then you'll get 5 * 4 .

Output

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

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