Skip to main content
 首页 » 编程设计

python之我在理解 round() 函数时缺少什么

2025年05月04日24xxx_UU

我正在查看 online doc for round() function在 python 中,它说,

round(number[, ndigits])

....The return value is an integer if called with one argument, otherwise of the same type as number.

所以,我写了下面的代码。

x = round(32.7) 
print 'x is now : ', x 
print str(type(x)) 
print type(x).__name__ 

让我解释一下我在上面的代码片段中使用的最后两个打印品。

  1. 第二次打印是通过反复试验的方法。 (今天是我学习 Python 的第一天)
  2. 第三个打印是引用this answer添加的.

令人惊讶的是,当前输出是

x is now : 33.0
<type 'float'>
float

我期待

x is now : 33
<type 'int'>
int

我没主意了。我错过了什么?

附言对于任何感兴趣的人, LIVE VERSION

请您参考如下方法:

在 python 2.x 中,round总是返回一个 float 。

根据打印语句的语法判断,您使用的是 python 2.x。