gpt4 book ai didi

python类分数

转载 作者:太空宇宙 更新时间:2023-11-04 09:06:34 25 4
gpt4 key购买 nike

我编写了一个代码,让用户以“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

最佳答案

使用 fractions.Fraction() class并让它为您完成工作:

>>> import fractions
>>> fractions.Fraction(2, 4)
Fraction(1, 2)

要自己简化分数,请计算最大公约数:

def gcd(a, b):
while b:
a, b = b, a%b
return a

g = gcd(numerator, denominator)
numerator //= g
denominator //= g

关于python类分数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20148813/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com