float is OK, int gives wrong output python 2.7 [duplicate]

妖精的绣舞 提交于 2019-12-02 19:02:25

问题


Possible Duplicate:
Why doesn’t this division work in python?

I have this and works fine

def roi(stake, profit):
    your_roi = profit / stake * 100
    return your_roi

def final_roi():
    roi1 = roi(52, 7.5)
    print "%.2f"  % roi1

final_roi()

but if I change the profit number to an int (meaning both stake and profit will have an int value) e.g. 52, 7 it is giving the output of 0.00. what's wrong there? I thought it had been formatted to be a float with the precision of two.


回答1:


In python2.x, / does integer division (the result is an integer, truncated downward) if both arguments are of type integer. The "easy" fix is to put:

from __future__ import division

at the very top of your script, or to construct a float out of one of the arguments before dividing:

your_roi = float(profit) / stake * 100

Python also has an integer division operator (//), so you can still perform integer division if desired -- even if you from __future__ import division




回答2:


If profit is integer, the division will be integer division instead of double division and you will have the result rounded down to the nearest integer number. Even if you format the number to float wehn printing it will still be 0 as it is rounded down on the assignment above.



来源:https://stackoverflow.com/questions/14565622/float-is-ok-int-gives-wrong-output-python-2-7

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!