我应该在我的阶乘计算器代码中添加或删除什么?

What should I add or remove on my factorial calculator code?

我是编码新手,所以我对应该在我的代码中添加或删除什么感到困惑。当我输入 2 的阶乘时,它也打印出阶乘 1,而我只想打印 2 的阶乘。

import java.util.Scanner;

public class FactorialCalculator {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        
        int i, fact = 1, number;
                
        System.out.println("<------ Factorial Calculator ------>");
        System.out.print("Enter a positive integer: ");
        number = input.nextInt();
        
        if (number <= 2) {
            for (i = 1; i<=number; i++) {
                fact = fact * i;
                System.out.println("2! = 1 x 2 ");
                System.out.println("The Factorial of 2 is: "+fact);             
            }
        }       
    }
}

输出:

<------ Factorial Calculator ------>
Enter a positive integer: 2
The Factorial of 2 is: 1
The Factorial of 2 is: 2

将您的打印语句移出循环。

if (number <= 2) {
     for (i = 1; i<=number; i++) {
          fact = fact * i;
     }
     System.out.println("The Factorial of 2 is: "+fact);             
}

但您可能希望允许比 2 更大的值。并且不要忘记 0!1! 都等于 1.

像这样尝试。

int fact = 1; //starting point for all factorials.
if (number >= 2) {
    for (int i = 2; i <= number; i++) {
         fact = fact * i;
    }
}
System.out.println(number + "! = " + fact);

我认为您混淆了 <= 2>= 2<= 2 只允许值 2, 1, 0, -1, etc 进入循环。您想要的是允许值 >= 22, 3, 4, ...