我有以下程序
def F_inf(a,b):
x1=a.numerator/a.denominator
x2=b.numerator/b.denominator
if x1<x2:
print "a<b"
elif x1>x2:
print "a>b"
else: print "a=b"
a=Fraction(10,4)
b=Fraction(10,4)
F_inf(a, b)
当我执行它时,x1只接收分数的整数值,例如,如果我必须计算2/4 x1等于0而不是0.5。 我该怎么办 ? 感谢
答案 0 :(得分:1)
听起来你正在使用Python2。最好的解决方案是切换到Python 3(不仅仅是因为划分而是因为"Python 2.x is legacy, Python 3.x is the present and future of the language")。
除此之外,你还有几个选择。
from __future__ import division
# include ^ as the first line in your file to use float division by default
或
a = 1
b = 2
c = a / (1.0*b) # multiplying by 1.0 forces the right side of the division to be a float
#c == 0.5 here