如何获得Fraction对象的提名者/分母

时间:2014-03-27 18:34:13

标签: python fractions

我有四个变量作为分数添加:

n1 = input("Denominator 1")
d1 = input("Denominator 1")
n2 = input("Denominator 1")
d2 = input("Denominator 1")

def fraction(n1,d1,n2,d2):
    a = Fraction(n1,d1)
    b = Fraction(n2,d2)
    print(a+b)
    return

fraction(n1,d1,n2,d2)

答案来自23/45

我如何将这两个数字分开并删除除数?

23
---
45

2 个答案:

答案 0 :(得分:2)

使用Fraction.numeratorFraction.denominator

>>> from fractions import Fraction
>>> a = Fraction(1, 2)
>>> b = Fraction(2, 3)
>>> tot = a+b
>>> print(tot, tot.numerator, tot.denominator)
7/6 7 6

答案 1 :(得分:2)

a = Fraction(n1, d1)
b = Fraction(n2, d2)
c = a+b
print(c.numerator, c.denominator, sep="\n---\n")

下次你需要这样的事情时,请dir(c)

你会得到类似的东西:

 [..., '_sub', 'conjugate', 'denominator', 'from_decimal', 'from_float', 'imag', 'limit_denominator', 'numerator', 'real']

(另外,help(c)或查看documentation很有用)