在java中打印阶乘计算过程

嗨,我需要打印析因计算的过程。 例如,如果用户输入为5,系统应打印出“5 * 4 * 3 * 2 * 1 = 120”

我有这个代码:

public static void factorial() { Scanner sc = new Scanner(System.in); int factorial = 1; int count; System.out.println(me+", This is option 2: Calculate a factorial"); System.out.print("Enter your number: "); int number = sc.nextInt(); System.out.println(); if (number>0) { for (count=1; count<=number; count++) factorial = factorial*count; System.out.println(" = "+factorial); System.out.println(); } else { System.out.println("Enter a positive whole number greater than 0"); System.out.println(); } } 

我试过插入这段代码:

  System.out.print(count+" * "); 

但输出为“1 * 2 * 3 * 4 * 5 * = 6”。 所以结果也是错误的。 我该如何更改代码? 谢谢

问题是你没有在你的for语句上加上大括号{}:

 if (number>0) { for (count=1; count<=number; count++) { factorial = factorial*count; System.out.print(count); if(count < number) System.out.print(" * "); } System.out.println("Factorial of your number is "+factorial); System.out.println(); } 

此外,如果您担心订单(1,2,4,5而不是5,4,3,2,1),您可以执行以下操作(更改for循环):

 if (number>0) { for (count=number; count>1; count--) { factorial = factorial*count; System.out.print(count); if(count > 2) System.out.print(" * "); } System.out.println("Factorial of your number is "+factorial); System.out.println(); } 

使用此代码。 它会检查您是否在最后一次迭代中,否则添加" * "

 System.out.print(count + ((count < number) ? " * " : "")); 

否则你也可以使用:

 for (count=1; count < number; count++) { // Note: < instead of <= factorial *= count; System.out.print(count + " * "); } factorial *= number; System.out.println(number + " = " + factorial); 

这样的事情应该能够实现你所期待的:

  int number = 5; int factorial = 1; String factString = ""; for (int count = number; count > 0; count--) { factorial = factorial * count; if (count == number) { factString += count; } else { factString += " * " + count; } } System.out.println("Factorial of " + factString + " is " + factorial); System.out.println(); 

代码将从输入的数字开始倒计时。 这将通过将进度存储在字符串中来打印所有行。