原文: https://beginnersbook.com/2014/01/java-program-to-find-factorial-of-a-given-number-using-recursion/

    在这里,我们将编写程序,使用递归找出数字的阶乘。

    程序 1:

    程序将提示用户输入数字。一旦用户提供输入,程序将计算所提供输入数的阶乘。

    1. /**
    2. * @author: BeginnersBook.com
    3. * @description: User would enter the 10 elements
    4. * and the program will store them into an array and
    5. * will display the sum of them.
    6. */
    7. import java.util.Scanner;
    8. class FactorialDemo{
    9. public static void main(String args[]){
    10. //Scanner object for capturing the user input
    11. Scanner scanner = new Scanner(System.in);
    12. System.out.println("Enter the number:");
    13. //Stored the entered value in variable
    14. int num = scanner.nextInt();
    15. //Called the user defined function fact
    16. int factorial = fact(num);
    17. System.out.println("Factorial of entered number is: "+factorial);
    18. }
    19. static int fact(int n)
    20. {
    21. int output;
    22. if(n==1){
    23. return 1;
    24. }
    25. //Recursion: Function calling itself!!
    26. output = fact(n-1)* n;
    27. return output;
    28. }
    29. }

    输出:

    1. Enter the number:
    2. 5
    3. Factorial of entered number is: 120

    程序 2:

    如果您不想要用户干预并且只想在程序中指定数字,请参考此示例。

    1. class FactorialDemo2{
    2. public static void main(String args[]){
    3. int factorial = fact(4);
    4. System.out.println("Factorial of 4 is: "+factorial);
    5. }
    6. static int fact(int n)
    7. {
    8. int output;
    9. if(n==1){
    10. return 1;
    11. }
    12. //Recursion: Function calling itself!!
    13. output = fact(n-1)* n;
    14. return output;
    15. }
    16. }

    输出:

    1. Factorial of 4 is: 24