Observe the following python program
def goo(y,x):
y = float(y)
x = float(x)
yup = (y - x - 1) / x
yup = str(yup)
yup = yup.split(".")
decimal = "." + yup[1]
decimal = float(decimal)
output = decimal / (1/x)
print output
print int(output)
goo(9,5)
When the program executes "print output" the answer is 3.0
When the program executes "print int(output)" the answer is 2
"print int(output)" should execute to deliver 3, not 2
Why is this happening?
解决方案
The default for the print statement is to round the value to the nearest. int() truncates.
>>> print 2.99999999999999
3.0
>>> print int(2.99999999999999)
2
If you want to see a more exact representation, use repr.
>>> print repr(2.9999999999999)
2.9999999999999