Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def 最大公因數(甲, 乙):
- return 甲 if 乙 == 0 else 最大公因數(乙, 甲%乙)
- class 分數:
- def __init__(self, 分子, 分母):
- self.分子 = 分子
- self.分母 = 分母
- def __str__(self):
- return (str(self.分子) + '/' + str(self.分母))
- def 約分(self):
- 約他 = 最大公因數(self.分子, self.分母)
- if 約他<0:
- 約他 = -約他
- self.分子 //= 約他
- self.分母 //= 約他
- return self
- def __mul__(self, other):
- return 分數(self.分子 * other.分子, self.分母 * other.分母).約分()
- def __add__(self, other):
- return 分數(self.分子*other.分母 + self.分母*other.分子, self.分母*other.分母).約分()
- def __sub__(self, other):
- return 分數(self.分子*other.分母 - self.分母*other.分子, self.分母*other.分母).約分()
- def __truediv__(self, other):
- return 分數(self.分子*other.分母, self.分母*other.分子).約分()
- def 換成小數(self):
- return self.分子 / self.分母
- def __lt__(self, other):
- return self.分子*other.分母 - self.分母*other.分子 < 0
- def __gt__(self, other):
- return other < self
- def __le__(self, other):
- return not self.__gt__(other)
- def __ge__(self, other):
- return not self.__lt__(other)
- def __eq__(self, other):
- return self.__ge__(other) and self.__le__(other)
- 數字 = 分數(2, 3)
- 另外一個數字 = 分數(1, 5);
- 軟軟的數字 = 分數(3, 8)
- print(數字 + 另外一個數字)
- print(數字 - 另外一個數字)
- print(另外一個數字 - 數字)
- print(軟軟的數字 * 數字)
- print(軟軟的數字 / 另外一個數字)
- print(另外一個數字.換成小數())
- print(數字 > 另外一個數字)
- print(數字 == 分數(2,3))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement