简体   繁体   English

自动将int转换为float

[英]Automatic int to float conversion

m = 10
x = 5
val = 1
print(type(val))
for i in range(1, x+1):
    val = (val * (m + i)) / (i)
    print(type(val))
    print(val)

Here initially val is of type int but in the loop it is getting converted to float although I am performing integer by integer division. 在这里,最初的valint类型的,但是在循环中,尽管我正在执行整数除法运算,但是它被转换为float Why is it so? 为什么会这样呢?

You have to use: // 您必须使用: //

val = (val * (m + i)) // (i)

And your val will remain being an integer 而且您的val将仍然是整数

The behavior of / was changed with this: https://www.python.org/dev/peps/pep-0238/ /的行为已通过以下方式更改: https : //www.python.org/dev/peps/pep-0238/

The operator module docs give also a hint about the separation between true division (returning a float) and floor division which returns the floor and therefore an int operator模块文档还给出了有关true division (返回浮点数)和floor division之间的分隔的提示, floor division返回地板,因此返回int

https://docs.python.org/3/library/operator.html https://docs.python.org/3/library/operator.html

It is specified in the Semantics for True division in PEP 238 : 它在PEP 238 真语义划分”中指定:

True division for int s and long s will convert the arguments to float and then apply a float division. intlong进行真除法会将参数转换为float ,然后应用float除法。 That is, even 2/1 will return a float ( 2.0 ), not an int . 也就是说,即使2/1也将返回float2.0 ),而不是int For float s and complex , it will be the same as classic division. 对于floatcomplex ,它将与经典除法相同。

So an automatic conversion is performed when an int is found. 因此,当找到一个int时,将执行自动转换。 Note that this is the default behaviour in Python 3. In python 2 you'll need to import from __future__ in order to have similar results. 请注意,这是Python 3中的默认行为。在python 2中,您需要从__future__ import ,以获得相似的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM