Ich habe ein Programm geschrieben, das 2 Brüche und einen Operator liest und gibt mir die Antwort, wenn ausgewertet. Beachten Sie die Länge des Codes, ich habe es nur hinzugefügt, um abgeschlossen zu sein. Meine Frage ist folgende: wenn ich als Eingabe eingebenVereinfachen Sie die Ausgabe rationals python3
12/23
23/12
*
Ich will es mir geben, die Ausgabe 1
. Aber es gibt mir 1/1
. Wie kann ich das korrigieren?
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")