Python 2.7中的除法。和3.3 [英] Division in Python 2.7. and 3.3
本文介绍了Python 2.7中的除法。和3.3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在Python 2.7中将两个数字相除并用小数点得到结果?
How can I divide two numbers in Python 2.7 and get the result with decimals?
我不明白为什么会有区别:
I don't get it why there is difference:
在Python 3中:
in Python 3:
>>> 20/15
1.3333333333333333
在Python 2中:
in Python 2:
>>> 20/15
1
这实际上不是模吗?
推荐答案
在python 2.7中,如果输入是整数,则 /
运算符是整数除法。
In python 2.7, the /
operator is integer division if inputs are integers.
如果要进行浮点除法(这是我一直喜欢的东西),只需使用以下特殊导入即可:
If you want float division (which is something I always prefer), just use this special import:
from __future__ import division
在此处查看:
>>> 7 / 2
3
>>> from __future__ import division
>>> 7 / 2
3.5
>>>
整数除法通过使用 //
,并使用%
Integer division is achieved by using //
, and modulo by using %
>>> 7 % 2
1
>>> 7 // 2
3
>>>
编辑
如 user2357112
所评论,此导入必须在任何其他常规导入之前完成。
As commented by user2357112
, this import has to be done before any other normal import.
这篇关于Python 2.7中的除法。和3.3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文