作业帮 > 综合 > 作业

C语言设计实现抽象数据类型"有理数"基本操作包括有理数的加法,减法,乘法,除法,以及求有理数的分子,分

来源:学生作业帮 编辑:搜搜考试网作业帮 分类:综合作业 时间:2024/05/02 06:42:49
C语言设计实现抽象数据类型"有理数"基本操作包括有理数的加法,减法,乘法,除法,以及求有理数的分子,分
最后是分母
C语言设计实现抽象数据类型
有理数即分数,
分数的数据类型是很简单的.
另外,求有理数的分子,分母的问题,因为给的有理数只能是有限小数,所以根本没有疑问.
但是如果改成:
求分子分母之和最小的,在一定误差范围内的分数,这个问题才有价值
比如:
0.3333333,如果误差为1e-4
那么1/3明显要比333333/10000000
下面给出一个实现(C++):
struct RatNum
{
int a,b;
static int GCD(int a,int b)
{
if(a<0)a=-a;
if(b<0)b=-b;
if(a==0)return b;
if(b==0)return a;
if(a<b)
{
int c=a;
a=b;
b=c;
}
unsigned int c;
while(c= a % b)
{
a = b ;
b = c;
}
return b;
}
explicit RatNum(int aa=0,int bb=1)
:a(aa),b(bb)
{
}
explicit RatNum(double num,double esp=0.00000001)
{
if(esp<0)esp=-esp;
for(b=1;;b++)
{
a=b*num+.5;
double k=a-b*num;
if(k<0)k=-k;
if(k<esp)break;
}
}
void norm()//约分
{
int c=GCD(a,b);
a/=c;
b/=c;
if(b<0)
{
a=-a;
b=-b;
}
}
RatNum operator/(const RatNum& f)const
{
RatNum d=*this;
d.a*=f.b;
d.b*=f.a;
return d;
}
RatNum operator-()const
{
RatNum ret=*this;
ret.a=-ret.a;
return ret;
}
void operator*=(const RatNum& f)
{
a*=f.a;
b*=f.b;
norm();
}
RatNum operator*(const RatNum& f)const
{
RatNum d=*this;
d*=f;
return d;
}
RatNum operator*(int q)const
{
RatNum d=*this;
d.a*=q;
return d;
}
void operator-=(const RatNum& f)
{
int bb=b;
a*=f.b;
b*=f.b;
a-=f.a*bb;
}
void operator+=(const RatNum& f)
{
int bb=b;
a*=f.b;
b*=f.b;
a+=f.a*bb;
}
void positive()
{
if (a<0)a=-a;
}
bool operator==(int n)
{
return a==n*b;
}
void operator=(int q)
{
a=q;
b=1;
}
};