[英]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);
}
}
我附加了代碼和輸出的圖像。 我只想不顯示輸入的結果。
如果我輸入數字5,則輸出應為;
Enter No: 5 >20 60 120 The factorial of 5 is 120
更改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
* 5
為5
)。 如果從5
開始並在循環測試中遞減,則將得到5 * 4
。
輸出量
Enter a number: 5
20
60
120
The factorial of 5 is 120
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.