python类分数 [英] python class fraction numbers
本文介绍了python类分数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我编写了一个代码,使用户可以以 d / n的形式输入两个分数。
I made a code that makes the user input two fraction numbers in the form "d/n".
如何使其打印出简化的形式?分数?
How can I make it print the reduced form of the fraction ?
例如:当我键入2/4时,它会显示1/2?
ex: when I type 2/4 it prints 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
推荐答案
使用 fractions.Fraction()
类,并让它为您完成工作:
Use the fractions.Fraction()
class and have it do the work for you:
>>> import fractions
>>> fractions.Fraction(2, 4)
Fraction(1, 2)
简化分数您自己,计算最大公约数:
To simplify fractions yourself, calculate the greatest common divisor:
def gcd(a, b):
while b:
a, b = b, a%b
return a
g = gcd(numerator, denominator)
numerator //= g
denominator //= g
这篇关于python类分数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文