Python 3中int()和floor()之间的区别是什么? [英] What is the difference between int() and floor() in Python 3?

查看:1756
本文介绍了Python 3中int()和floor()之间的区别是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python 2中, floor()返回一个浮点值。虽然对我来说不是很明显,但我发现了一些解释,澄清了为什么 floor()返回float(例如 float(' inf') float('nan'))。然而,在Python 3中, floor()会返回整数(并返回前面提到的特殊情况的溢出错误)。
$ b $

那么 int()之间有什么区别, floor() now?

解决方案

floor()轮向下 int() 截断。当您使用负数时,区别很明显:

 >>>导入数学
>>> math.floor(-3.5)
-4
>>> int(-3.5)
-3

向下舍入负数意味着它们移开从0开始,截断将它们移近0。



换句话说, floor()总是要低于或等于原来的。 int()会接近零或相等。


In Python 2, floor() returned a float value. Although not obvious to me, I found a few explanations clarifying why it may be useful to have floor() return float (for cases like float('inf') and float('nan')).

However, in Python 3, floor() returns integer (and returns overflow error for the special cases mentioned before).

So what is the difference, if any, between int() and floor() now?

解决方案

floor() rounds down. int() truncates. The difference is clear when you use negative numbers:

>>> import math
>>> math.floor(-3.5)
-4
>>> int(-3.5)
-3

Rounding down on negative numbers means that they move away from 0, truncating moves them closer to 0.

Putting it differently, the floor() is always going to be lower or equal to the original. int() is going to be closer to zero or equal.

这篇关于Python 3中int()和floor()之间的区别是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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