分数模板
虽经过博主大量测试,但仍可能存在bug,可以向博主反馈以及时修改
该模板可兼容能支持各种基本操作的高精度模板
使用方法
先把模板贴上,再加上
using namespace Fraction;
//或者
using Fraction::Frac;
下面均以分子分母在int范围内的分数为例
定义
Frac<int>x;//定义一个初值为0的分数
Frac<int>x(a);//定义一个初值为a的分数
Frac<int>x(a,b);//定义一个初值为a/b的分数
运算
可以将分数与各种类型的数据(例如\(int,long\ long\))进行运算,返回的结果是一个分数
逻辑运算符返回的结果为0或者1
支持的运算有
//算术运算符
a+b ,a-b ,a*b ,a/b
//取相反数,自增,自减
-a, --a, a--, ++a ,a++
//逻辑运算符
a&&b ,a||b ,!a ,a>=b ,a==b ,a<=b ,a>b ,a<b
//赋值运算符
a+=b ,a-=b ,a*=b ,a/=b ,a=b
模板
namespace Fraction{
template<typename Int>Int gcd(Int a,Int b){return b?gcd(b,a%b):a;}
template<typename Int>Int abs(Int a){return a<0?-a:a;}
template<typename Int>struct Frac{
Int a,b;
Frac(){a=(Int)0;b=(Int)1;}
Frac(Int x){a=x;b=(Int)1;}
Frac(Int x,Int y){a=x;b=y;}
Frac &operator =(Int x){a=x;b=1;return *this;}
double to_double(){return (double)a/b;}
Frac rec(){assert(a);return Frac(b,a);}
Frac operator-(){return (Frac){-a,b};}
Frac&operator++(){a+=b;return*this;}
Frac&operator--(){a-=b;return*this;}
Frac&operator+=(Frac x){
Int g=gcd(b,x.b);
a=b/g*x.a+x.b/g*a; b*=x.b/g;
g=gcd(abs(a),b);a/=g;b/=g;
return*this;
}
Frac&operator-=(Frac x){return*this+=-x;}
Frac&operator*=(Frac x){
Int g1=gcd(abs(a),x.b),g2=gcd(abs(x.a),b);
(a/=g1)*=x.a/g2;(b/=g2)*=x.b/g1;
return*this;
}
Frac&operator/=(Frac x){return*this*=x.rec();}
Frac friend operator +(Frac x,Frac y){return x+=y;}
Frac friend operator -(Frac x,Frac y){return x-=y;}
Frac friend operator *(Frac x,Frac y){return x*=y;}
Frac friend operator /(Frac x,Frac y){return x/=y;}
int operator !(){return a;}
int friend operator &&(Frac x,Frac y){return x.a&&y.a;}
int friend operator ||(Frac x,Frac y){return x.a||y.a;}
#define logical_operator(op) int friend operator op(Frac x,Frac y){return (x-y).a op 0;}
logical_operator(<)
logical_operator(>)
logical_operator(<=)
logical_operator(>=)
logical_operator(==)
/*
friend ostream&operator<<(ostream&ostr,Frac x){
ostr<<x.a;
assert(x.b);
if(x.b!=1)ostr<<"/"<<x.b;
return ostr;
}
*///输出一个分数,一般用不上,要用取消注释并使用std::cout即可
};
#undef logical_operator
}