|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
请大神帮忙修改一下,报错不知道怎么改
class Rational:
"""定义有理数类"""
def __init__(self,a,b):
(a,b)=(b,a)if a>b else(a,b)
for i in range(1,b + 1):
if((a % i == 0) and (b % i == 0)):
c=i
self.a=a/c
self.b=b/c
# 提示:使用辗转相除法,求a,b最大公约数m
# 实现有理数的显示和输出 如Rational(1,3)输出为 "1/3" "a/b"
def __rstr__(self):
print("self.a/self.b")
# 实现有理数的四则运算,+,-,*,/“”“这里好像要计算出c d放回Rational(c,d)”“”
def __add__(self,other):
return __add__(self, other)
def __sub__(self, other):
return __sub__(self, other)
def __mul__(self,other):
return __mul__(self,other)
def __truediv__(self, other):
return __truediv__(self, other)
# 实现有理数的比较 ==, !=, <, >.
def __eq__(self,other):
if float(self)-float(other)==0:
return True
else:
return False
def __ne__(self,other):
if float(self)-float(other)!=0:
return True
else:
return False
def __gt__(self,other):
if float(self)-float(other)<0:
return True
else:
return False
def __lt__(self,other):
if float(self)-float(other)>0:
return True
else:
return False
“”“让以下可以正常运行”“”
r1 = Rational(3,4)
r2 = Rational(4,5)
r3 = r1 + r2
r4 = r1 - r2
r5 = r1 * r2
r6 = r1 / r2
print(r1,r2,r3,r4,r5,r6)
print(r1 < r2)
print(Rational(25,0))
class Rational(int):
"""定义有理数类"""
def __new__(cls, a, b):
(a, b) = (b, a) if a > b else (a, b)
for i in range(1, b + 1):
if ((a % i == 0) and (b % i == 0)):
c = i
cls.a = a / c
cls.b = b / c
return c
# 提示:使用辗转相除法,求a,b最大公约数m
# 实现有理数的显示和输出 如Rational(1,3)输出为 "1/3" "a/b"
def __rstr__(self):
print("self.a/self.b")
# 实现有理数的四则运算,+,-,*,/“”“这里好像要计算出c d放回Rational(c,d)”“”
def __add__(self, other):
return int.__add__(self, other)
def __sub__(self, other):
return int.__sub__(self, other)
def __mul__(self, other):
return int.__mul__(self, other)
def __truediv__(self, other):
return int.__truediv__(self, other)
# 实现有理数的比较 ==, !=, <, >.
def __eq__(self, other):
if float(self) - float(other) == 0:
return True
else:
return False
def __ne__(self, other):
if float(self) - float(other) != 0:
return True
else:
return False
def __gt__(self, other):
if float(self) - float(other) < 0:
return True
else:
return False
def __lt__(self, other):
if float(self) - float(other) > 0:
return True
else:
return False
r1 = Rational(3,4)
r2 = Rational(4,5)
r3 = r1 + r2
r4 = r1 - r2
r5 = r1 * r2
r6 = r1 / r2
print(r1,r2,r3,r4,r5,r6)
print(r1 < r2)
print(Rational(25,0))
|
|