分数类模板

· · 个人记录

rt

支持分数间加减乘除,以及分数和小数的加减乘除,还有输入输出重载。

分数的符号以分子的正负号表示。 可以用这个去水掉~~烂题~~ NOIP2020T1(记得开`__int128`)。 # code ```c++ #include <bits/stdc++.h> //#define int int64_t //#define int __int128 //#define MOD (1000000007) //#define eps (1e-6) #define endl '\n' #define debug_endl cout<<endl; #define debug cout<<"debug"<<endl; using namespace std; struct Rnumber{ int a,b; inline Rnumber(){ a=0,b=1; } inline Rnumber(int _a,int _b){ a=_a,b=_b; } inline void limit(int &_a,int &_b){//内置化简/统一分数格式 if(_b<0) _a=-_a,_b=-_b; //正负号统一在分子上 if(b==0) exit(486); //b=0不是个实数,返回错误 int flag=(_a<0?-1:1); //以免gcd输入负数 int t=__gcd(_a*flag,_b); //分数化简 _a/=t,_b/=t; _a*=flag; } //重载运算符 inline Rnumber operator+(const Rnumber& other){//分数+分数 int _a=a*other.b+other.a*b,_b=other.b*b; limit(_a,_b); return Rnumber(_a,_b); } inline Rnumber operator-(const Rnumber& other){//分数-分数 int _a=a*other.b-other.a*b,_b=other.b*b; limit(_a,_b); return Rnumber(_a,_b); } inline Rnumber operator*(const Rnumber& other){//分数*分数 int _a=a*other.a,_b=other.b*b; limit(_a,_b); return Rnumber(_a,_b); } inline Rnumber operator/(const Rnumber& other){//分数/分数 int _a=a*other.b,_b=other.a*b; limit(_a,_b); return Rnumber(_a,_b); } inline Rnumber operator+(const int& other){//分数+整数 int _a=a+other*b,_b=b; limit(_a,_b); return Rnumber(_a,_b); } inline Rnumber operator-(const int& other){//分数-整数 int _a=a-other*b,_b=b; limit(_a,_b); return Rnumber(_a,_b); } inline Rnumber operator*(const int& other){//分数*整数 int _a=a*other,_b=b; limit(_a,_b); return Rnumber(_a,_b); } inline Rnumber operator/(const int& other){//分数/整数 int _a=a,_b=b*other; limit(_a,_b); return Rnumber(_a,_b); } //以下对应上面基本二元运算符的一元形式 inline Rnumber operator+=(const Rnumber& other){ *this=*this+other; return *this; } inline Rnumber operator-=(const Rnumber& other){ *this=*this-other; return *this; } inline Rnumber operator*=(const Rnumber& other){ *this=*this*other; return *this; } inline Rnumber operator/=(const Rnumber& other){ *this=*this/other; return *this; } inline Rnumber operator+=(const int& other){ *this=*this+other; return *this; } inline Rnumber operator-=(const int& other){ *this=*this-other; return *this; } inline Rnumber operator*=(const int& other){ *this=*this*other; return *this; } inline Rnumber operator/=(const int& other){ *this=*this/other; return *this; } friend std::istream& operator>>(std::istream& is, Rnumber& f) {//重载输入 is>>f.a>>f.b; return is; } friend std::ostream& operator<<(std::ostream& os, const Rnumber& f) {//重载输出 os<<f.a<<' '<<f.b; return os; } }; signed main(){ //freopen(".in","r",stdin); //freopen(".out","w",stdout); Rnumber a,b; int c; cout<<"输入分数a:"; cin>>a; cout<<"输入分数b:"; cin>>b; cout<<"输入整数c:"; cin>>c; cout<<"你输入的分数为:"<<a<<endl<<b<<endl; cout<<"a+b:"<<a+b<<endl; cout<<"a-b:"<<a-b<<endl; cout<<"a*b:"<<a*b<<endl; cout<<"a/b:"<<a/b<<endl; cout<<"a+c:"<<a+c<<endl; cout<<"a-c:"<<a-c<<endl; cout<<"a*c:"<<a*c<<endl; cout<<"a/c:"<<a/c<<endl; return 0; } ```