由于python决定a = 1/3为int,因此将a的值设为0,这是非常不期望的。 我相信阅读完整的文档将对此进行解释,但是Google的大量搜索都没有找到此问题的简单答案。
答案 0 :(得分:1)
在Python2中,两个int
的除法将是int
。但是在python3中它是固定的。
>>type(1/3)
<type 'int'>
如果您想让它们在Python2中浮动:
>>from __future__ import division
>>type(1/3)
<type 'float'>
或者您可以通过将其中之一强制转换为float来获得结果:
>>type(1/float(3))
<type 'float'>
在Python3中,/
的结果将是float
,而//
的结果将是整数。
In [1]: type(1/3)
Out[1]: float
In [2]: type(1//3)
Out[2]: int
答案 1 :(得分:1)
a=1/3
是一个表达式,被评估为int / int,它产生一个int结果。
a=0.3
是未评估的值,是浮点数。
答案 2 :(得分:0)
@UlrichEckhardt是正确的,在Python 3中,这是您得到的:
>>> a=1/3
>>> a
0.3333333333333333
>>> type(a)
<class 'float'>
>>>
但是在Python 2中,至少一个值应为float:
>>> a=1.0/3
>>> a
0.3333333333333333
>>> type(a)
<class 'float'>
>>>
或者:
>>> a=1/3.0
>>> a
0.3333333333333333
>>> type(a)
<class 'float'>
>>>
答案 3 :(得分:0)
python2和python3之间有区别:
使用python2:
$python
Python 2.7.6 (default, Nov 13 2018, 12:45:42)
>>> type(1/3)
<type 'int'>
>>> type(0.3)
<type 'float'>
使用python3:
$python3
Python 3.6.1 (default, Dec 19 2018, 09:17:24)
>>> type(1/3)
<class 'float'>
>>> type(0.3)
<class 'float'>
简短地:
/
与整数一起使用时将意味着整数除法,那么1/3
仅= 0
->整数。/
甚至与整数一起使用也意味着实数除法,然后1/3
= 0.33333...
->浮点数。