在这段代码中,我试图添加分数,我想知道如何获得1 1/4而不是(1,1,4)的输入。此代码还假设在不使用Class Fractions的情况下添加分数。任何帮助都会很棒,谢谢。
class Fraction:
def _gcd(a ,b):
while b:
a, b = b, a % b
return(a)
def _lcm(a ,b):
return(a * b // Fraction._gcd(a, b))
def __init__(self, numerator, denominator) :
if denominator < 0:
denominator *= -1
numerator *= -1
self.num = numerator
self.den = denominator
def __add__ (self, other) :
new_denominator = Fraction._lcm(self.den, other.den)
new_numerator = self.num*new_denominator//self.den + other.num*new_denominator//other.den
GCD = Fraction._gcd(new_numerator, new_denominator)
new_numerator = new_numerator // GCD
new_denominator = new_denominator // GCD
if new_numerator > new_denominator :
whole = new_numerator // new_denominator
new_numerator = new_numerator%new_denominator
return (whole, new_numerator, new_denominator)
else :
return (new_numerator, new_denominator)
def __sub__(self, other):
temp = Fraction(-1 * other.num, other.den)
return(self + temp)
num1 = Fraction(2,4)
num2 = Fraction(15,20)
print(num1.__add__(num2))
答案 0 :(得分:1)
这似乎很难解释......
如果这是格式问题,"{} {}/{}".format(1, 1, 4)
会将"1 1/4"
作为字符串给您,这是您想要的吗?然后,您可以调整它以使用代码的变量。
如果我没有做对,你应该尝试更好地解释你的问题。
参考文献:
https://docs.python.org/3.4/library/stdtypes.html#str.format