分数类(自动化简)

#include<bits/stdc++.h>
using namespace std;
class frac{
    private:
        int z,m;
    public:
        frac(int x=0,int y=1){
            z=x,m=y;
            fixed();
        }
        frac fixed(){
            int gcd=__gcd(abs(z),abs(m));
            if(m<0){
                m*=-1;z*=-1;
            }
            if(z==0){
                m=1;return;
            }
            if(gcd==0) return *this;
            z/=gcd;m/=gcd;
            return *this;
        }
        frac upside(){
            return frac(m,z);
        }
        frac operator = (pair<int,int>A){
            z=A.first;m=A.second;fixed();
            return *this;
        }
        frac operator + (frac A){
            return (frac(z*A.m+m*A.z,m*A.m)).fixed();
        }
        frac operator * (frac A){
            return (frac(z*A.z,m*A.m)).fixed();
        }
        frac operator / (frac A){
            return (*this*A.upside()).fixed();
        }
        frac operator -(){
            return frac(-z,m);
        }
        frac operator -(frac A){
            return *this+(-A);
        }
        bool operator <(frac A){
            return z*A.m<A.z*m;
        }
        bool operator ==(frac A){
            return z*A.m==A.z*m;
        }
        bool operator >(frac A){
            return !(*this==A and *this<A);
        }
        void print(){
            fixed();
            cout<<z<<"/"<<m<<endl;
        }
};
posted @ 2024-09-23 17:17  HaneDaniko  阅读(14)  评论(0编辑  收藏  举报