1. 程式人生 > >java c c++語言 計算階乘

java c c++語言 計算階乘

import java.util.Scanner;
public class C201_07_06計算階乘 {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.printf("輸入一個數:");
        int num = scan.nextInt();

        int result = factorial(num);
        System.out.println(result);
    }
    /**
     * 計算階乘
     * @param num 輸入的數
     * @return 返回階乘結果
     */
    private static int factorial(int num) {
        int result = 1;
        if (num == 0) {
            return 1;
        }
        return num*factorial(num-1);
        /*for (int i = 1; i <= num; i++) {
            result *=i;
        }//普通for迴圈寫
        return result;*/
    }
}

5!=120

6!=720