简化输出有理数 python3
Simplify output rationals python3
我编写了一个程序,它读取 2 个分数和一个运算符,并在评估时给出答案。不要介意代码的长度,我只是添加它是为了完整。我的问题如下:当我作为输入输入时
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")
因为在内部如何存储这两个相等的数字并不重要,所以您唯一需要修改的方法是 __str__
,它执行外部表示:
def __str__ ( self ):
if self.d == 1:
return "%d" % self.n
return "%d/%d" % ( self.n, self.d )
这将正确处理 n / 1
的所有情况,包括 1 / 1
。
我编写了一个程序,它读取 2 个分数和一个运算符,并在评估时给出答案。不要介意代码的长度,我只是添加它是为了完整。我的问题如下:当我作为输入输入时
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")
因为在内部如何存储这两个相等的数字并不重要,所以您唯一需要修改的方法是 __str__
,它执行外部表示:
def __str__ ( self ):
if self.d == 1:
return "%d" % self.n
return "%d/%d" % ( self.n, self.d )
这将正确处理 n / 1
的所有情况,包括 1 / 1
。