python - 在 Python 中,整数除法中向零舍入的好方法是什么?

标签 python rounding division negative-number integer-division

1/2

给予

0

应该如此。然而,

-1/2

给予

-1

,但我希望它向 0 舍入(即我希望 -1/2 为 0),无论它是正数还是负数。最好的方法是什么?

最佳答案

进行浮点除法然后转换为整数。不需要额外的模块。

Python 3:

>>> int(-1 / 2)
0
>>> int(-3 / 2)
-1
>>> int(1 / 2)
0
>>> int(3 / 2)
1

Python 2:

>>> int(float(-1) / 2)
0
>>> int(float(-3) / 2)
-1
>>> int(float(1) / 2)
0
>>> int(float(3) / 2)
1

关于python - 在 Python 中,整数除法中向零舍入的好方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19919387/

相关文章:

html - 如何设置父 div 宽度以匹配 a/img?

c# - 在 .NET 中除两位小数时出现溢出异常

java - 递归除以 3

python - python ctypes中的多维char数组(字符串数组)

python - 无法使用 python 和 pyserial 打开/dev/ttyusb0

sql - 这两个舍入表达式的值不同吗?

c# - 为什么c#不能计算数学函数的精确值

python - 列出索引超出范围与 Pandas read_csv

python - 如何安装这个轮子?

sql - 为什么我的小数值在 SQL 插入中会四舍五入为整数?