phan so

Class phan so

package phanso;

import java.util.Scanner;

public class PHANSO {

    int tu; int mau;

    //Phuong thuc khoi tao mac dinh

    public PHANSO() {

        tu=0; mau=1;

    }

    //Phuong thuc khoi tao khi biet tu va mau so

    public PHANSO(int t, int m)  {

        tu=t; mau=m;

    }

     //Phuong thuc khoi tao tu 1 phan so

    public PHANSO(PHANSO p) {

        this.tu=p.tu;

        this.mau=p.mau;

    }

    //Ham nhap va xuat phan so

    public void NhapPS() {

        Scanner sc = new Scanner(System.in);

        System.out.print("Nhap tu so = ");

        tu = sc.nextInt();

        System.out.print("Nhap mau so =");

        mau = sc.nextInt();

    }

    public void XuatPS() {

        if(mau == 1)

            System.out.println(tu);

        else

                System.out.println(+tu+"/"+mau);

    }

    //Ham tim USLN cuA 2 so nguyen

    public int UCLN(int a, int b) {

        if(a<0)

            a=-a;

        if(b<0)

            b=-b;

        while(a!=b)

        {

            if(a>b)

                a=a-b;

            else

                b=b-a;

        }

        return a+b;

    }

    //Ham tim BSCNN cua 2 so nguyen

    public int BSCNN(int a, int b) {

        return (a*b/UCLN(a,b));

       

    }

    //Phuong thuc rut gon phan so

    public PHANSO RutGonPhanSo(PHANSO ps) {

        int tmp;

        tmp=UCLN(ps.tu,ps.mau);

        ps.tu=ps.tu/tmp;

        ps.mau=ps.mau/tmp;

        return ps;

       

    }

    //Phuong thuc cong 2 phan so

    public PHANSO CongPhanSo(PHANSO p1,PHANSO p2) {

        PHANSO p3=new PHANSO();

        p3.tu=(p1.tu*p2.mau)+(p1.mau*p2.tu);

        p3.mau=p1.mau*p2.mau;

        p3=p3.RutGonPhanSo(p3);

        return p3;

    }

   

           

    public static void main(String[] args) {

        // TODO code application logic here

 

    }

}

Class main

 

public class DEMO {

    public static void main(String[] args){

        PHANSO ps1=new PHANSO();

        //Khoi gan cho phan so thu 2

        PHANSO ps2=new PHANSO(4,5);

        PHANSO ps3=new PHANSO();

       

        System.out.println("Nhap phan so thu nhat");

        ps1.NhapPS();

        System.out.print("Phan so thuPhan so thu 2 =");

        ps2.XuatPS();

       

        System.out.print("Tong 2 phan so =");

        ps3=ps3.CongPhanSo(ps1, ps2);

        ps3.XuatPS();

    }

   

}

Bạn đang đọc truyện trên: AzTruyen.Top

Tags: