加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 函数int()向负无穷大(floor)舍入或为零?

发布时间:2020-12-16 23:53:19 所属栏目:Python 来源:网络整理
导读:我看到Why is -1/2 evaluated to 0 in C++,but -1 in Python?在Python中表示整数除法向无穷大舍入,即地板应用于结果. 我认为int(value)也会做类似floor的事情,而我在实践中得到int(-1.5)== -1,在我的脑海中预计为-2. 所以问题是:为什么整数除法和函数int()

我看到Why is -1/2 evaluated to 0 in C++,but -1 in Python?在Python中表示整数除法向无穷大舍入,即地板应用于结果.

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

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

最佳答案
int()删除小数部分;它没有做任何舍入.从documentation:

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

为了将浮点数转换为int,这完全是逻辑行为.这不是分区,地板或其他.

//楼层划分运算符否则清楚地做楼层,而不是截断.在Python 2中,对于两个整数操作数,/ division也是floor. documentation再次:

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

其中math.floor()记录为:

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

我觉得这里没有矛盾;划分楼层,将浮点数转换为整数截断.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读