我有一个类的这一部分,它取一个整数和一个分数并将它们加在一起。
def __add__(self, g):
whole_add=self.whole_number + g.whole_number
numerator = (self.fraction.numerator * g.fraction.denominator ) + (g.fraction.numerator * self.fraction.denominator)
denominator = self.fraction.denominator * g.fraction.denominator
f=Fraction(numerator,denominator)
return '{} and {}'.format(whole_add,f)
fraction_1 = Fraction(3, 4)
fraction_2 = Fraction(2, 3)
mixed_num_1 = MixedNumber(2, fraction_1)
mixed_num_2 = MixedNumber(1, fraction_2)
print(mixed_num_1 + mixed_num_2)
结果是3和17/12,当它应该是4和5/12时,我不知道如何做到这一点,我假设如果分数是> = 1.任何帮助将是非常感谢
答案 0 :(得分:3)
如果您使用fractions
library,则可以对所有内容求和,然后取出分数的int()
部分:
def __add__(self, g):
summed = sum((self.whole_number, g.whole_number, self.fraction, g.fraction))
whole = int(summed)
remainder = summed - whole
return '{} and {}'.format(whole, remainder)
Fraction()
类为您实现__add__
,您可以只对整数和Fraction()
对象进行求和,这一切都可以正常工作。
使用常量进行演示:
>>> from fractions import Fraction
>>> summed = sum((2, 1, Fraction(3, 4), Fraction(2, 3)))
>>> whole = int(summed)
>>> remainder = summed - whole
>>> '{} and {}'.format(whole, remainder)
'4 and 5/12'
一个鲜为人知但却很方便的事实是,int()
类型的Python具有.numerator
和.denominator
属性,fractions.Fraction()
类使用。如果您不使用fractions
库,您可以自己使用它:
def __add__(self, g):
summed = 0
for v in (self.whole_number, g.whole_number, self.fraction, g.fraction):
summed = Fraction(summed.numerator * v.denominator +
v.numerator * summed.denominator,
summed.denominator * v.denominator)
whole = summed._numerator // summed._denominator
remainder = Fraction(summed.numerator * whole.denominator -
whole.numerator * summed.denominator,
summed.denominator * whole.denominator)
return '{} and {}'.format(whole, remainder)
答案 1 :(得分:1)
“修复”您的版本的一种方法是直接处理不正确的分数:
whole_add=self.whole_number + g.whole_number
numerator = (self.fraction.numerator * g.fraction.denominator ) + (g.fraction.numerator * self.fraction.denominator)
denominator = self.fraction.denominator * g.fraction.denominator
whole_add += numerator // denominator
numerator -= numerator % denominator
f=Fraction(numerator,denominator)
return '{} and {}'.format(whole_add,f)
虽然有更有效的方法可以更直接地进行这种添加。