分数类重载


#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
typedef long long LL;
LL gcd(LL a,LL b)
{
    return b==0?a:gcd(b,a%b);
}
struct Fraction{
    LL num,den;
    Fraction(LL num=0,LL den=1){
        if(den<0)
        {
            num=-num;
            den=-den;
        }
        assert(den!=0);
        LL g=gcd(abs(num),den);
        this->num = num/g;
        this->den = den/g;
    }
    Fraction operator +(const Fraction &o)const {
        return Fraction(num*o.den+den*o.num,den*o.den);
    }
    Fraction operator -(const Fraction &o)const {
        return Fraction(num*o.den-den*o.num,den*o.den);
    }
    Fraction operator *(const Fraction &o)const {
        return Fraction(num*o.num,den*o.den);
    }
    Fraction operator /(const Fraction &o)const {
        return Fraction(num*o.den,den*o.num);
    }
    bool operator <(const Fraction &o)const {
        return num*o.den<den*o.num;
    }
    bool operator ==(const Fraction &o)const {
        return num*o.den==den*o.num;
    }
};
int main()
{
    Fraction a,b,ans;
    cin>>a.num>>a.den;
    cin>>b.num>>b.den;
    ans = a+b;
    cout<<ans.num<<" "<<ans.den<<endl;
    ans = a-b;
    cout<<ans.num<<" "<<ans.den<<endl;
    ans = a*b;
    cout<<ans.num<<" "<<ans.den<<endl;
    ans = a/b;
    cout<<ans.num<<" "<<ans.den;
    return 0;
}


你可能感兴趣的:(分数类重载)