Java 实例 使用递归查找给定数字的阶乘

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

程序 1:

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

/**
 * @author: BeginnersBook.com
 * @description: User would enter the 10 elements
 * and the program will store them into an array and 
 * will display the sum of them.
 */
import java.util.Scanner;
class FactorialDemo{
   public static void main(String args[]){
      //Scanner object for capturing the user input
      Scanner scanner = new Scanner(System.in);
      System.out.println("Enter the number:");
      //Stored the entered value in variable
      int num = scanner.nextInt();
      //Called the user defined function fact
      int factorial = fact(num);
      System.out.println("Factorial of entered number is: "+factorial);
   }
   static int fact(int n)
   {
       int output;
       if(n==1){
         return 1;
       }
       //Recursion: Function calling itself!!
       output = fact(n-1)* n;
       return output;
   }
}

输出:

Enter the number:
5
Factorial of entered number is: 120

程序 2:

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

class FactorialDemo2{
   public static void main(String args[]){
      int factorial = fact(4);
      System.out.println("Factorial of 4 is: "+factorial);
   }
   static int fact(int n)
   {
       int output;
       if(n==1){
         return 1;
       }
       //Recursion: Function calling itself!!
       output = fact(n-1)* n;
       return output;
   }
}

输出:

Factorial of 4 is: 24
赞(0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

Java 实例