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

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

概述我看到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.

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

以上是内存溢出为你收集整理的python – 函数int()向负无穷大(floor)舍入或为零?全部内容,希望文章能够帮你解决python – 函数int()向负无穷大(floor)舍入或为零?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1207859.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-04
下一篇 2022-06-04

发表评论

登录后才能评论

评论列表(0条)

保存