如何在控制台中找到阶乘并显示计数结果?

How to find factorial and show result of counting in console?

public class Car {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        System.out.println(n+"!="+factorial(n));
    }
    public static int factorial(int num) {
        return (num == 0) ? 1 : num * factorial (num - 1);
    }
}

如何使此代码在控制台中显示文本 3! = 1*2*3 = 6

不要为此使用递归。此外,它并不是真正有效或必要的。

      Scanner in = new Scanner(System.in);
      int n = in.nextInt();
      int fact = 1;
      String s = n + "! = 1";
      for (int i = 2; i <= n; i++) {
         fact *= i;
         s += "*" + i;
      }
      s += " = ";
      System.out.println(s + fact); 


有很多方法可以做到这一点,例如您可以在计算 factorial 时构建所需的字符串或打印轨迹。在下面的例子中,我做了前者。

顺便说一句,你应该检查输入是否是正整数。

import java.util.Scanner;

public class Car {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter a positive integer: ");
        int n = in.nextInt();
        if (n >= 0) {
            StringBuilder strFact = new StringBuilder();
            int fact = factorial(n, strFact);
            if (strFact.length() > 0) {
                // Delete the last '*'
                strFact.deleteCharAt(strFact.length() - 1);
                System.out.println(n + "!= " + strFact + " = " + fact);
            } else {
                System.out.println(n + "!= " + fact);
            }
        } else {
            System.out.println("This is an invalid input.");
        }
    }

    public static int factorial(int num, StringBuilder strFact) {
        int fact;
        if (num == 0) {
            fact = 1;
        } else {
            fact = num * factorial(num - 1, strFact);
            strFact.append(num + "*");
        }
        return fact;
    }
}

样本运行:

Enter an integer: 3
3!= 1*2*3 = 6