2024-05-23 16:18:59 发布
网友
我是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。这些是作者的错误还是我做错了什么?
5//4
4/2
2/4
我在linux2上使用Python 2.7.4,[GCC 4.7.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。除时,int4和2尚未定义为floats。
2.0
4/float(2)
4
2
floats
希望有帮助!
这种差异发生在Python 3.x的情况下。 在Python 3.0中,7 / 2将返回3.5,而7 // 2将返回3。运算符/是floating point division,运算符//是floor division或integer division。
Python 3.x
7 / 2
7 // 2
/
floating point division
floor division
integer division
但在Python 2.x的情况下,不会有任何差异,我相信文本是错误的,这是我得到的输出。
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..],而//用于请求“经典/楼层除法”。
4/3 = 1.3333..
如果希望在Python2.7中启用“真除法”,可以在代码中使用from __future__ import division。
from __future__ import division
来源:PEP 238
例如:
>>> 4/3 1 >>> 4//3 1 >>> from __future__ import division >>> 4/3 1.3333333333333333 >>> 4//3 1
//
似乎工作正常请参阅关于运算符的tutorial。
要使
4/2
等于2.0
,需要指定一个浮点数。例如:4/float(2)
计算结果为2.0
。除时,int4
和2
尚未定义为floats
。希望有帮助!
这种差异发生在
Python 3.x
的情况下。 在Python 3.0中,7 / 2
将返回3.5,而7 // 2
将返回3。运算符/
是floating point division
,运算符//
是floor division
或integer division
。但在
Python 2.x
的情况下,不会有任何差异,我相信文本是错误的,这是我得到的输出。在Python2.x中,默认的除法运算符是“经典除法”。这意味着,当使用整数运算符时,^ {CD1}}将导致与C++或java类似的整数除法[即^ {< CD2> }。
在Python3.x中,这是改变的。在这里,
/
指的是“真除法”[4/3 = 1.3333..
],而//
用于请求“经典/楼层除法”。如果希望在Python2.7中启用“真除法”,可以在代码中使用
from __future__ import division
。来源:PEP 238
例如:
相关问题 更多 >
编程相关推荐