Java Source - Bài tập tính giai thừa(Calculate Factorial).





Bài tập tính giai thừa của một số bằng cách nhập số bất kỳ vào chương trình. Đây là một trong những bài tập đầu tiên khi học vòng for(For Loop).







CalculateNumberFactorial.java
 /**
 * @(#)CalculateNumberFactorial.java
 *
 * CalculateNumberFactorial application
 *
 * @author VNLIVES.NET
 * @version 1.00 2013/9/30
 */

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class CalculateNumberFactorial {

    public static void main(String[] args) {
         
        int number = 0;
          
        try
        {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            System.out.print("Vui long nhap so can tinh giai thua: ");
            number = Integer.parseInt(br.readLine());          
        }
      
        catch(NumberFormatException ex)
        {
            System.out.println("Du lieu nhap khong hop le: " + ex);
            System.exit(0);
        }
     
        catch(IOException ioe)
        {
            System.out.println("Loi IO truy xuat du lieu :" + ioe);
            System.exit(0);
        }      
     
        /*
         * --------------------------------
         * Vi du, gai thua cua 4 is 4*3*2*1.
        */
     
        int factorial = number;
     
        for(int i =(number - 1); i > 1; i--)
        {
            factorial = factorial * i;
        }

        System.out.println("Giai thua cua " + number + " là " + factorial);
    }
  
}

Sau khi chạy chương trình và nhập số 5 để tính giai thừa thì kết quả sẽ là 120 như hình bên dưới.











No comments:

Post a Comment