float 没问题,int 给出错误的输出 python 2.7

float 没问题,int 给出错误的输出 python 2.7

问题描述:

可能的重复:
为什么这个划分在 python 中不起作用?

我有这个并且工作正常

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()

但是如果我将利润数字更改为 int(意味着权益和利润都将具有 int 值)例如52, 7 它给出了 0.00 的输出.有什么问题吗?我认为它已被格式化为精度为 2 的浮点数.

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.

在 python2.x 中,/ 做整数除法(结果是一个整数,向下截断)如果两个参数都是整数类型.简单"的解决方法是:

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 也有一个整数除法运算符 (//),因此您仍然可以根据需要执行整数除法 -- 即使您 from __future__ import Division

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