class Rational(object):
def __init__(self, p, q):
self.p = p
self.q = q
def __add__(self, r):
return Rational(self.p * r.q + self.q * r.p, self.q * r.q)
def __sub__(self, r):
return Rational(self.p * r.q - self.q * r.p, self.q * r.q)
def __mul__(self, r):
return Rational(self.p * r.p , self.q * r.q)
def __div__(self, r):
return Rational(self.p * r.q , self.q * r.p)
def __str__(self):
if self.p>self.q:
miner=self.q
maxer=self.p
else:
miner=self.p
maxer=self.q
a,b=judegement(miner,maxer)
if self.p>self.q:
return '%s/%s' %(b,a)
else:
return '%s/%s' %(a,b)
def judgement(miner,maxer):
for i in range(miner+1):
if maxer%i==0:
maxer=maxer/i
miner=miner/i
return judegment(miner,maxer)
return miner,maxer
__repr__ = __str__
r1 = Rational(1, 2)
r2 = Rational(1, 4)
print r1 + r2
print r1 - r2
print r1 * r2
print r1 / r2题目是:Rational类虽然可以做加法,但无法做减法、乘方和除法,请继续完善Rational类,实现四则运算。自己想的化简过程哪出错啊~,帮我看看,谢谢慕友啦
添加回答
举报
0/150
提交
取消