Floor division with negative number(负数楼层划分)
问题描述
The expression 6 // 4
yields 1
, where floor division produces the whole number after dividing a number.
But with a negative number, why does -6 // 4
return -2
?
The //
operator explicitly floors the result. Quoting the Binary arithmetic operations documentation:
the result is that of mathematical division with the ‘floor’ function applied to the result.
Flooring is not the same thing as rounding to 0; flooring always moves to the lower integer value. See the math.floor()
function:
Return the floor of x, the largest integer less than or equal to x.
For -6 // 4
, first the result of -6 / 4
is calculated, so -1.5
. Flooring then moves to the lower integer value, so -2
.
If you want to round towards zero instead, you'll have to do so explicitly; you could do this with the int()
function on true division:
>>> int(-6 / 4)
-1
int()
removes the decimal portion, so always rounds towards zero instead.
这篇关于负数楼层划分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:负数楼层划分
基础教程推荐
- 使用 Google App Engine (Python) 将文件上传到 Google Cloud Storage 2022-01-01
- 如何在 Python 中检测文件是否为二进制(非文本)文 2022-01-01
- 使 Python 脚本在 Windows 上运行而不指定“.py";延期 2022-01-01
- 症状类型错误:无法确定关系的真值 2022-01-01
- Python 的 List 是如何实现的? 2022-01-01
- 使用Python匹配Stata加权xtil命令的确定方法? 2022-01-01
- 将 YAML 文件转换为 python dict 2022-01-01
- 如何在Python中绘制多元函数? 2022-01-01
- 哪些 Python 包提供独立的事件系统? 2022-01-01
- 合并具有多索引的两个数据帧 2022-01-01