2017-10-19 32 views
-2

在此代码中,我试图添加分数,我想知道如何得到1 1/4而不是(1,1,4)的输入。此代码也假设不使用类分数来添加分数。任何帮助将是伟大的,谢谢。Python - 添加分数

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)) 
+1

可以请你减少你的 “问题”,以包括期望的行为,因此您的实际问题? –

+0

我在问如何得到1 1/4的输出而不是1,1,4 –

+0

你的意思是你想把它作为一个字符串而不是元组返回吗? 'return“{} {}/{}”.format(whole,new_numerator,new_denominator)'应该有效。 – anupsabraham

回答

1

这似乎很不好解释...

如果是格式化的问题,"{} {}/{}".format(1, 1, 4)会给你"1 1/4"作为一个字符串,是你想要的吗?然后你可以调整它来处理你的代码的变量。

如果我没有弄清楚,你应该尽量更好地解释你的问题。

参考文献:

https://docs.python.org/3.4/library/stdtypes.html#str.format

https://pyformat.info/

+0

对不起,我没有解释清楚,即时通讯真的很新的这个东西.... –

+0

这是好的,我敢肯定你的下一个问题将是更详细:) 每个人都有权做一个初学者。 –