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
答案 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
* 5
是5
)。如果您从5
开始并在循环测试中递减,那么您将获得5 * 4
。
<强>输出强>
Enter a number: 5
20
60
120
The factorial of 5 is 120