我在java中創建了一個程序,它接受一個int作爲輸入並打印它的階乘。例如,輸入= 5打印:5 x 4 x 3 x 2 x 1 = 120.但是,我無法找到一種方法來擺脫結尾處的乘法符號。我得到:5 x 4 x 3 x 2 x 1 x = 120.我能做些什麼才能最終擺脫它?這裏是我的代碼:如何在循環的階乘表達式的結尾處打印乘號?
import java.util.*;
public class Factorial {
public static void factorial(int input)
{
int sum = 1;
for(int i = input; i>=1; i--)
{
System.out.print(i+" x ");
sum *= i;
}
System.out.print(" = " + sum);
}
public static void main (String []args)
{
Scanner in = new Scanner (System.in);
System.out.println("Enter a number to obtain its factorial");
int a = in.nextInt();
factorial(a);
}
}