2.7.4上的Python/and//运算符

2024-05-13 16:04:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python新手,我开始学习基础知识。我是C++的人,所以//操作符是新的东西。根据我正在读的一本书:

>> 4/2
2.0
>> 2/4
0.5
>> 5//4
2
>> 2//4
0

问题是,当我写5//4时,结果是1;当我写4/2时,结果是2,而不是2.0;当我写2/4时,结果是0。我必须写“2.0/4.0”才能得到0.5。这些是作者的错误还是我做错了什么?

我在linux2上使用Python 2.7.4,[GCC 4.7.3]


Tags: 错误作者gcc基础知识新手linux2
3条回答

//似乎工作正常

请参阅关于运算符的tutorial

// = Floor Division - The division of operands where the result is the quotient in which the digits after the decimal point are removed. 9//2 is equal to 4 and 9.0//2.0 is equal to 4.0

要使4/2等于2.0,需要指定一个浮点数。例如:4/float(2)计算结果为2.0。除时,int42尚未定义为floats

希望有帮助!

这种差异发生在Python 3.x的情况下。 在Python 3.0中,7 / 2将返回3.5,而7 // 2将返回3。运算符/floating point division,运算符//floor divisioninteger division

但在Python 2.x的情况下,不会有任何差异,我相信文本是错误的,这是我得到的输出。

Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on 
win32 
Type "copyright", "credits" or "license()" for more information.
>>> 4/2
2
>>> 2/4
0
>>> 5//4
1
>>> 2//4
0
>>> 

在Python2.x中,默认的除法运算符是“经典除法”。这意味着,当使用整数运算符时,^ {CD1}}将导致与C++或java类似的整数除法[即^ {< CD2> }。

在Python3.x中,这是改变的。在这里,/指的是“真除法”[4/3 = 1.3333..],而//用于请求“经典/楼层除法”。

如果希望在Python2.7中启用“真除法”,可以在代码中使用from __future__ import division

来源:PEP 238

例如:

>>> 4/3
1
>>> 4//3
1
>>> from __future__ import division
>>> 4/3
1.3333333333333333
>>> 4//3
1

相关问题 更多 >