我需要编写一个程序来调整用户给出的必须满足某些条件的数字的阶乘。这必须使用非嵌套的do-while循环来完成 我已设法验证输入。它甚至可以计算出最多12个int的正确因子。 当输入为13时,它输出错误的答案。
这就是我所拥有的:
int factorial = 1;
int x = 1;
int i = 0;
do {
if ( i > 0) {
factorial *= x;
x--;
//I added this line to see what was going on and found that at
//some point it would output a negative value
System.out.println(factorial + " x " + x);
continue;
}
if (myScanner.hasNextInt()) {
x = myScanner.nextInt();
i = 1;
if (x < 9 || x > 16) {
System.out.println("Invalid input, enter again:");
x = 1;
i = 0;
}
}
else {
String invalid = myScanner.nextLine();
System.out.println("Invalid input, enter again:");
}
}
while (x > 0);
System.out.println("Answer is: " + factorial);
}//end main method
当我输入13时,这就是我得到的:
Please enter an integer that is between 9 and 16:
13
13 x 12
156 x 11
1716 x 10
17160 x 9
154440 x 8
1235520 x 7
8648640 x 6
51891840 x 5
259459200 x 4
1037836800 x 3
//Everything works fine until here. Why? How can I fix it?
-1181456896 x 2
1932053504 x 1
1932053504 x 0
Answer is: 1932053504