1
我寫了一個程序,讀取2個分數和一個運算符,並在評估時給出答案。不要介意代碼的長度,我只是添加它是完整的。我的問題是這樣的:當我輸入簡化輸出合理性python3
12/23
23/12
*
我希望它給我的輸出1
進入。但它給了我1/1
。我該如何解決這個問題?
x = input().split('/')
y = input().split('/')
z = input()
def gcd (a, b):
if b == 0:
return a
else:
return gcd(b, a%b)
class Rational:
def __init__ (self, a=0, b=1):
g = gcd (a, b)
self.n = a/g
self.d = b/g
def __add__ (self, other):
return Rational (self.n * other.d + other.n * self.d,
self.d * other.d)
def __sub__ (self, other):
return Rational (self.n * other.d - other.n * self.d,
self.d * other.d)
def __mul__ (self, other):
return Rational (self.n * other.n, self.d * other.d)
def __div__ (self, other):
return Rational (self.n * other.d, self.d * other.n)
def __str__ (self):
return "%d/%d" % (self.n, self.d)
def __float__ (self):
return float (self.n)/float (self.d)
q = Rational()
w = Rational()
q.n = int(x[0])
q.d = int(x[1])
w.n = int(y[0])
w.d = int(y[1])
answer = eval("q"+z+"w")