def gcd(m,n):
while m%n != 0:
oldm = m
oldn = n
m = oldn
n = oldm%oldn
return n
class Fraction:
def init(self,top,bottom):
self.num = top
self.den = bottom
if self.den<0:
self.den = -self.den
self.num = -self.num
def show(self):
print(self.num,"/",self.den)
def __str__(self):
return str(self.num)+"/"+str(self.den)
def __add__(self,otherfraction):
newnum = self.num * otherfraction.den + self.den * otherfraction.num
newden = self.den * otherfraction.den
common = gcd(newnum,newden)
return Fraction(newnum//common,newden//common)
def __sub__(self,otherfraction):
newnum = self.num * otherfraction.den - self.den * otherfraction.num
newden = self.den * otherfraction.den
common = gcd(newnum,newden)
return Fraction(newnum//common,newden//common)
def __mul__(self,otherfraction):
newnum = self.num * otherfraction.num
newden = self.den * otherfraction.den
common = gcd(newnum,newden)
return Fraction(newnum//common,newden//common)
想在里面添加try excpet直接用于在调用函数时判断分子分母是否为整数,比如Fraction(1.5,1.5)就会直接报错,应该怎么添加。
try是用来捕获异常的,抛出异常要用raise
你这里if判断输入的格式,如果不符合要求就raise,跟try没有一毛钱关系