Advertisement
Guest User

Untitled

a guest
Dec 6th, 2019
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.74 KB | None | 0 0
  1. def 最大公因數(,):
  2.   returnif== 0 else 最大公因數(, 甲%乙)
  3.  
  4. class 分數:
  5.   def __init__(self, 分子, 分母):
  6.     self.分子 = 分子
  7.     self.分母 = 分母
  8.   def __str__(self):
  9.     return (str(self.分子) + '/' + str(self.分母))
  10.   def 約分(self):
  11.     約他 = 最大公因數(self.分子, self.分母)
  12.     if 約他<0:
  13.       約他 = -約他
  14.     self.分子 //= 約他
  15.     self.分母 //= 約他
  16.     return self
  17.   def __mul__(self, other):
  18.     return 分數(self.分子 * other.分子, self.分母 * other.分母).約分()
  19.   def __add__(self, other):
  20.     return 分數(self.分子*other.分母 + self.分母*other.分子, self.分母*other.分母).約分()
  21.   def __sub__(self, other):
  22.     return 分數(self.分子*other.分母 - self.分母*other.分子, self.分母*other.分母).約分()
  23.   def __truediv__(self, other):
  24.     return 分數(self.分子*other.分母, self.分母*other.分子).約分()
  25.   def 換成小數(self):
  26.     return self.分子 / self.分母
  27.   def __lt__(self, other):
  28.     return self.分子*other.分母 - self.分母*other.分子 < 0
  29.   def __gt__(self, other):
  30.     return other < self
  31.   def __le__(self, other):
  32.     return not self.__gt__(other)
  33.   def __ge__(self, other):
  34.     return not self.__lt__(other)
  35.   def __eq__(self, other):
  36.     return self.__ge__(other) and self.__le__(other)  
  37.  
  38. 數字 = 分數(2, 3)
  39. 另外一個數字 = 分數(1, 5);
  40. 軟軟的數字 = 分數(3, 8)
  41. print(數字 + 另外一個數字)
  42. print(數字 - 另外一個數字)
  43. print(另外一個數字 - 數字)
  44. print(軟軟的數字 * 數字)
  45. print(軟軟的數字 / 另外一個數字)
  46. print(另外一個數字.換成小數())
  47. print(數字 > 另外一個數字)
  48. print(數字 == 分數(2,3))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement