c/c++语言开发共享分数模板

分数模板 虽经过博主大量测试,但仍可能存在bug,可以向博主反馈以及时修改 该模板可兼容能支持各种基本操作的高精度模板 使用方法 先把模板贴上,再加上 下面均以分子分母在int范围内的分数为例 定义 运算 可以将分数与各种类型的数据(例如$int,long long$)进行运算,返回的结果是一个分 …


分数模板

虽经过博主大量测试,但仍可能存在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>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 }

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/c-cdevelopment/607291.html

(0)
上一篇 2021年5月14日
下一篇 2021年5月14日

精彩推荐