函数int()向负无穷大(floor)舍入或为零? [英] Function int() rounding towards negative infinity (floor) or zero?

查看:210
本文介绍了函数int()向负无穷大(floor)舍入或为零?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到为什么在C ++中,-1 / 2评估为0,但在Python中为-1?表示Python中的整数除法向无穷大舍入,即 floor 应用于结果。

I see Why is -1/2 evaluated to 0 in C++, but -1 in Python? says integer division rounds towards infinity in Python, namely, floor is applied to the result.

我认为 int(value)也会做类似 floor ,而我在实践中得到 int(-1.5)== -1 ,预计 -2 在我的脑海里。

I thought int(value) would also do something like floor, while I get int(-1.5) == -1 in practice, which was expected to be -2 in my mind.

所以问题是:为什么规则在整数除法和函数 int()之间不一致?有没有合理的解释?

So question is: why rules are inconsistent between integer division and function int()? Is there any reasonable explanation?

推荐答案

int()删除小数零件;它没有做任何舍入。来自文档

int() removes the decimal component; it doesn't do any rounding. From the documentation:


如果x是浮点数,则转换将截断为零。

If x is floating point, the conversion truncates towards zero.

用于转动 float 进入 int 这完全是逻辑行为。这是分区,地板或其他。

For turning a float into an int this is entirely logical behaviour. This is not division, flooring or otherwise.

// 楼层划分运营商否则显然 地板,而不是截断。在Python 2中,对于两个整数操作数, / 除法也是底层。再次文档

The // floor division operator otherwise clearly does floor, not truncate. In Python 2, for two integer operands, the / division also floors. The documentation again:


结果是数学除法的结果,其中'floor'函数应用于结果

the result is that of mathematical division with the ‘floor’ function applied to the result

其中 math.floor() 记录为:

where math.floor() is documented as:


返回 x 的最低值一个浮点数,小于或等于 x 的最大整数值。

Return the floor of x as a float, the largest integer value less than or equal to x.

我认为这里没有矛盾;划分楼层,将浮点数转换为整数截断值。

I see no inconsistency here; division floors, turning floats to integers truncates.

这篇关于函数int()向负无穷大(floor)舍入或为零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆