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

满意答案

00e27ab806e4881f8254fe7ae8741834.png

jiduyumenzhe

推荐于 2017.11.24

00e27ab806e4881f8254fe7ae8741834.png

采纳率: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分享举报

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值