[英]Java Factorial loop
The problem is that the factorial value is updating in a while loop
I think that is the problem why.问题是阶乘值在
while loop
中更新,我认为这就是问题所在。 Here is the code这是代码
while (true) {
System.out.print("Enter a positive integer: ");
n = sc.nextInt();
if (n > 0) {
System.out.print(n + "! = ");
for (int i = 1; i <= n; i++) {
factorial = factorial * i;
for (int j = 1; j <= n; j++) {
if (j == n) System.out.printf("%d", j);
else System.out.printf("%d x ", j);
}
System.out.println("");
System.out.println("The factorial of " + n + " is " + factorial);
}
} else {
System.out.println("Invalid input");
break;
}
}
Okay, so here is the problem when the first input is 5好的,这是第一个输入为 5 时的问题
The factorial of 5 is: 120
But on the second input it goes like this when I tried to input like for example 4但是在第二个输入上,当我尝试输入例如 4 时,它是这样的
The factorial of 4 is: 2880
it goes higher even though the factorial of 4 is 24即使 4 的阶乘为 24,它也会变高
Just add factorial = 1;
只需添加
factorial = 1;
after the else block.在 else 块之后。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.