本文主要是介绍c语言设计实现抽象数据类型有理数基本操作包括有理数加法减法乘法,设计实现抽象数据类型“有理数”。基本操作包括有理数的加法,减法,乘法,除法,以及求有理数的分子,分...,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
满意答案
jiduyumenzhe
推荐于 2017.11.24
采纳率:41% 等级:12
已帮助:10463人
有理数即分数,
分数的数据类型是很简单的。
另外,求有理数的分子,分母的问题,因为给的有理数只能是有限小数,所以根本没有疑问。
但是如果改成:
求分子分母之和最小的,在一定误差范围内的分数,这个问题才有价值
比如:
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
{
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
}
}
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;
}
};
40分享举报
这篇关于c语言设计实现抽象数据类型有理数基本操作包括有理数加法减法乘法,设计实现抽象数据类型“有理数”。基本操作包括有理数的加法,减法,乘法,除法,以及求有理数的分子,分...的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!