python实现分数的加减乘除
#!/usr/bin/env python# -*- coding: utf-8 -*-# @Time : 2021/7/15 13:43# @Author : wutiandedef gcd(a,b):if b==0:return aelse:return gcd(b,a%b)def lcm(a,b):d = gcd(a,b)return a//d*bclass Fraction:def __i
·
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/7/15 13:43
# @Author : wutiande
def gcd(a,b):
if b==0:
return a
else:
return gcd(b,a%b)
def lcm(a,b):
d = gcd(a,b)
return a//d*b
class Fraction:
def __init__(self,up,down):
"""成员变量"""
if down == 0:
raise("分母不能为0")
self.up = up
self.down = down
def reduction(self):
"""约分"""
if self.down < 0: # 分母为负数,分子分母同时取反
self.up = -self.up
self.down = -self.down
if self.up == 0: # 分子为0,分母为1
self.down = 1
else:
d = gcd(abs(self.up),abs(self.down)) # 求最大公约数,化简
self.up //=d
self.down //=d
def __add__(self, other):
"""加法"""
up = self.up*other.down + other.up*self.down
down = self.down*other.down
f = Fraction(up,down)
f.reduction() #约分
return f
def __sub__(self, other):
"""减法"""
up = self.up * other.down - other.up * self.down
down = self.down * other.down
f = Fraction(up, down)
f.reduction() # 约分
return f
def __mul__(self, other):
"""乘法"""
up = self.up * other.up
down = self.down * other.down
f = Fraction(up, down)
f.reduction() # 约分
return f
def __truediv__(self, other):
up = self.up * other.down
if other.up == 0:
raise("不能除以0")
down = self.down * other.up
f = Fraction(up, down)
f.reduction() # 约分
return f
if __name__ == '__main__':
f1 = Fraction(1,3)
f2 = Fraction(1,2)
f3 = f1-f2
f4 = f1*f2
f5 = f1/f2
f6 = f1+f2
print(f3.up,f3.down)
print(f4.up,f4.down)
print(f5.up,f5.down)
print(f6.up, f6.down)
-1 6
1 6
2 3
5 6
点击阅读全文
更多推荐
所有评论(0)