"d/n"형식의 두 분수를 사용자가 입력하게하는 코드를 만들었습니다.파이썬 클래스 소수 번호
어떻게 축소 된 형태의 분수를 인쇄 할 수 있습니까?
예 : 2/4를 입력하면 1/2이 인쇄됩니까?
import sys
class Rational:
def __init__(self,n,d):
self.numerator= n
self.denominator= d
def value(self):
return float(self.numerator)/float(self.denominator)
def __repr__(self):
return "%d/%d ~ %g" % (self.numerator,self.denominator,self.value())
def read(self):
while 1:
try:
s=raw_input("Enter fraction n/d: ")
n,d= s.split("/")
self.numerator= int(n)
self.denominator= int(d)
except KeyboardInterrupt:
print
exit()
except:
print sys.exc_info()[0]
print "bad input, try again."
else:
if int(d)==0:
print "The denominator cannot be zero. Try again."
elif int(d)<0:
print "The denominator cannot be negative. Try again."
else:
return
r1=Rational(1,1)
r1.read()
print r1
r2=Rational(1,1)
r2.read()
print r2
분수 모듈의 존재를 알고 있습니까? – Ant