Python 2.7 中的除法。和 3.3

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21316968/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 22:33:59  来源:igfitidea点击:

Division in Python 2.7. and 3.3

pythonpython-2.7python-3.3division

提问by Erzsebet

How can I divide two numbers in Python 2.7 and get the result with decimals?

如何在 Python 2.7 中将两个数字相除并得到带小数的结果?

I don't get it why there is difference:

我不明白为什么会有区别:

in Python 3:

在 Python 3 中:

>>> 20/15
1.3333333333333333

in Python 2:

在 Python 2 中:

>>> 20/15
1

Isn't this a modulo actually?

这实际上不是模数吗?

采纳答案by bgusach

In python 2.7, the /operator is integer division if inputs are integers.

在 python 2.7 中,/如果输入是整数,则运算符是整数除法。

If you want float division (which is something I always prefer), just use this special import:

如果你想要浮动除法(这是我一直喜欢的东西),只需使用这个特殊的导入:

from __future__ import division

See it here:

在这里看到它:

>>> 7 / 2
3
>>> from __future__ import division
>>> 7 / 2
3.5
>>>

Integer division is achieved by using //, and modulo by using %

整数除法是通过 using 实现的//,模数是通过 using%

>>> 7 % 2
1
>>> 7 // 2
3
>>>

EDIT

编辑

As commented by user2357112, this import has to be done before any other normal import.

正如 评论的那样user2357112,此导入必须在任何其他正常导入之前完成。

回答by mhlester

In Python 3, /is float division

在 Python 3 中,/是浮点除法

In Python 2, /is integer division (assuming intinputs)

在 Python 2 中,/是整数除法(假设int输入)

In both 2 and3, //is integer division

在 23 中,//都是整数除法

(To get float division in Python 2 requires either of the operands be a float, either as 20.or float(20))

(要在 Python 2 中获得浮点除法,需要两个操作数之一是浮点数,要么是20.要么float(20)

回答by woozyking

In Python 2.x, make sure to have at least one operand of your division in float. Multiple ways you may achieve this as the following examples:

在 Python 2.x 中,确保在float. 您可以通过多种方式实现这一点,例如以下示例:

20. / 15
20 / float(15)

回答by Bryan

"/" is integer division in python 2 so it is going to round to a whole number. If you would like a decimal returned, just change the type of one of the inputs to float:

“/”是python 2中的整数除法,因此它将四舍五入为整数。如果您希望返回小数,只需将其中一个输入的类型更改为浮点数:

float(20)/15 #1.33333333

float(20)/15 #1.33333333