如何以编程方式表示阶乘

时间:2018-08-24 15:32:27

标签: java output factorial

我找不到合适的头衔。

我写了一个小程序来计算给定整数的阶乘。该程序运行正常。现在,我还要打印其表示形式,假设我们有4个输入,程序将输出24个,然后打印Because 4! = 4 x 3 x 2 x 1

public class Test {
    static int factorial(int n){    
        if (n == 0)    
            return 1;    
        else    
            return(n * factorial(n-1));    
    }

    public static void main(String args[]){
        System.out.println("Enter a number:");
        Scanner sc = new Scanner(System.in);
        int i;
        int fact;
        int number= sc.nextInt();//Get user input and calculate its factorial    
        fact = factorial(number);   
        System.out.println("Factorial of " + number + " is " + fact);
        System.out.println("Because " + number+"!" + " = " + number + "x" + (number - 1) ); // This is what I tried so far
    } 
}

最后一个println显示了我尝试过的内容。但是,我只能输出4! = 4 x 3,无法下降到1。

0 个答案:

没有答案