public static void main(String[] args) {
// Luke Mihalovich
Scanner keyboard = new Scanner(System.in);
int n;
System.out.print("Enter a non-negative integer (-1 to quit) : ");
n = keyboard.nextInt();
int factorial = Factorial(n);
while (n >= 1) {
System.out.print("Enter a non-negative integer (-1 to quit) : ");
n = keyboard.nextInt();
System.out.println(n + "! = " + factorial);}
if (n == 0) {
System.out.print(n = 1); }
if (n == -1) {
System.out.print("Goodbye!"); }
}
public static int Factorial(int n) {
int factorial = 1;
for(int i= 1;i<n;) {
i++;
factorial = factorial * i; }
return factorial;
}
}
该程序为所有输入打印相同的结果。
例如,如果我输入5
,则答案正确为5! = 120
。但是,如果我输入4
,则会再次打印4! = 120
,这是错误的,应该是24
。
答案 0 :(得分:0)
您写道:
int factorial = Factorial(n);
while (n >= 1) {
// ...
System.out.println(n + "! = " + factorial);
}
未经更新 factorial
。像
int factorial = Factorial(n);
仅执行一次且未进行实时链接,以便在您更新n
后重新计算。
因此,您需要在每次迭代中明确更新factorial
:
int factorial = Factorial(n);
while (n >= 1) {
// ...
factorial = Factorial(n);
System.out.println(n + "! = " + factorial);
}
请坚持命名惯例。方法名称应始终以小写字符开头,因此它应为factorial
。然后应该将变量重新命名为result
,例如。
您的 for-loop 看起来很奇怪。您可以使用常用符号并运行到<= n
,甚至可以跳过i = 1
并直接从i = 2
开始:
for (int i = 2; i <= n; i++) {
factorial = factorial * i;
}
答案 1 :(得分:0)
在while循环中输入输入之后,你没有计算阶乘,而是你正在做的是在while循环之前计算一次阶乘,并在每次给出新输入时打印。
按如下方式更新主要功能,它应该可以正常工作。
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int n=1;
while (n >= 1) {
System.out.print("Enter a non-negative integer (-1 to quit) : ");
n = keyboard.nextInt();
// Calculate the factorial for each number you take as the input
int factorial = Factorial(n);
System.out.println(n + "! = " + factorial);}
if (n == 0) {
System.out.print(n = 1); }
if (n == -1) {
System.out.print("Goodbye!"); }
}