分数运算模板!!fraction!!

羡慕羡慕


#include <cassert>
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <stdlib.h>

using namespace std;
typedef long long ll;

ll gcd(ll a,ll b){
    return b?gcd(b,a%b):a;
}
struct frac{
    ll up,low;
    frac(ll up=0,ll low=1){
        if(low<0) up=-up,low=-low;
        assert(low);
        ll g=gcd(abs(up),low);
        this->up=up/g,this->low=low/g;
    }
    frac operator + (const frac &b) const
    {
        return frac(up * b.low + low * b.up, low * b.low);
    }
    frac operator - (const frac &b) const
    {
        return frac(up * b.low - low * b.up, low * b.low);
    }
    frac operator * (const frac &b) const
    {
        return frac(up * b.up, low * b.low);
    }
    frac operator / (const frac &b) const
    {
        return frac(up * b.low, low * b.up);
    }
    bool operator < (const frac &b) const
    {
        return up * b.low < low * b.up;
    }
    bool operator == (const frac &b) const
    {
        return up * b.low == low * b.up;
    }
    bool operator > (const frac& b) const
    {
        return b < *this;
    }
    bool operator <= (const frac& b) const
    {
        return !(b < *this);
    }
    bool operator >= (const frac &b) const
    {
        return !(*this < b);
    }
    bool operator != (const frac &b) const
    {
        return up * b.low != low * b.up;
    }
    frac operator += (const frac &b)
    {
        return *this = *this + b;
    }
    frac operator -= (const frac &b)
    {
        return*this = *this - b;
    }
    frac operator *= (const frac &b)
    {
        return *this = *this * b;
    }
    frac operator /= (const frac &b)
    {
        return *this = *this / b;
    }

};

int main()
{
    frac a,b;
    a.up=1;
    a.low=2;
    b.up=1;b.low=3;
    frac c=a/b;
    printf("%I64d %I64d\n",c.up,c.low);
}

太好啦~~~~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值