# -*- coding: utf-8 -*-
"""
利用欧几里得算法实现一个分数类,支持分数的四则运算(加法)
"""
class Fraction:
def __init__(self, a, b):
self.a = a
self.b = b
x = self.gcd(a, b)
self.a /= x
self.b /= x
def gcd(self, a, b):
while b > 0:
r = a % b
a = b
b = r
return a
# 最小公倍数
def zgs(self, a, b):
# 12 16 -> 4
# 3*4*4=48
x = self.gcd(a, b)
return a * b / x
# 加法
def __add__(self, other):
a = self.a
b = self.b
c = other.a
d = other.b
fenmu = self.zgs(b, d)
fenzi = a * fenmu / b + c * fenmu / d
return Fraction(fenzi, fenmu)
def __str__(self):
return "%d/%d" % (self.a, self.b)
a = Fraction(1, 3)
b = Fraction(1, 2)
print(a + b)
标签:__,return,--,欧几里得,fenmu,Fraction,除法,self,def
From: https://www.cnblogs.com/zylyehuo/p/17643452.html