2.9

mail@pastecode.io avatar
unknown
c_cpp
2 years ago
2.1 kB
1
Indexable
Never
#include <iostream>
using namespace std;

int GCD(int x,int y)
{
    while(x % y != 0)
    {
        int temp = x % y;
        x  = y;
        y = temp;
    }
    return y;
}
struct PhanSo
{
    int ts;
    int ms;
    //default "this" is pointer
    void Nhap(int ts,int ms)
    {
        this->ts = ts;
        if(ms != 0)
        {
            this->ms = ms;
        }
        else
        {
            cout<<"Mau so khong duoc bang 0\n";
            exit(EXIT_FAILURE);
        }

    }
    void Nhap()
    {
        int ts,ms;

        cout<<"Tu so : ";
        cin>>ts;
        this->ts = ts;

        cout<<"Mau so : ";
        cin>>ms;

        if(ms != 0)
        {
            this->ms = ms;
        }
        else
        {
            cout<<"Mau so khong duoc bang 0\n";
            exit(EXIT_FAILURE);
        }
    }
    void Xuat()
    {
        cout<<ts<<"/"<<ms<<endl;
    }

    //Operator Overloading
    PhanSo operator +(PhanSo ps2)
    {
        this->ts = this->ts * ps2.ms + this->ms * ps2.ts;
        this->ms = this->ms * ps2.ms;
        return *this;
    }
    PhanSo operator -(PhanSo ps2)
    {
        this->ts = this->ts * ps2.ms - this->ms * ps2.ts;
        this->ms= this->ms * ps2.ms;
        return *this;
    }
    PhanSo operator -()
    {
        this->ts = -this->ts;
        return *this;
    }
    PhanSo operator *(PhanSo ps2)
    {
        this->ts *= ps2.ts;
        this->ms *= ps2.ms;
        return *this;
    }
    PhanSo operator /(PhanSo ps2)
    {
        if(ps2.ts == 0)
        {
            cout<<"khong the chia!\n";
        }
        this->ts *= ps2.ms;
        this->ms *= ps2.ts;
        return *this;
    }
    //rut gon
    PhanSo RutGon()
    {
        int gcd = GCD(this->ts,this->ms);
        this->ts /= gcd;
        this->ms /= gcd;
        return *this;
    }
};
typedef PhanSo PhanSo;
int main()
{
    PhanSo ps1,ps2,ps3,ps;
    ps1.Nhap(2,3);
    ps2.Nhap(3,5);
    ps3.Nhap(7,6);
    ps = -ps1 / ps2 + ps3;
    ps.RutGon().Xuat();
    return 0;
}