我在理解 round() 函数时缺少什么?
What am I missing in understanding round() function?
我正在查看 python 中的 online doc for round()
function,上面写着,
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__
让我解释一下我在上面的片段中使用的最后两张印刷品。
- 第二次打印是通过试错法。 (今天是 Python 的第一天)
- 第三个打印是参考this answer添加的。
令人惊讶的是,当前输出是
x is now : 33.0
<type 'float'>
float
我期待
x is now : 33
<type 'int'>
int
我没主意了。我错过了什么?
P.S。对于任何感兴趣的人,LIVE VERSION
在 python 2.x 中,round
总是 returns 一个浮点数。
根据打印语句的语法判断,您在 python 2.x.
而不是使用 round...!试试这个,因为 round 函数是对浮点值进行舍入..
然而,round 和类型转换为 int 都做同样的工作 @ background
希望这对您有所帮助..!!
x = int(32.7)
print 'x is now :',x
print str(type(x))
print type(x).__name__
或
y=32.7
x=int(y)
print 'x is now :',x
print str(type(x))
print type(x).__name__
我正在查看 python 中的 online doc for round()
function,上面写着,
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__
让我解释一下我在上面的片段中使用的最后两张印刷品。
- 第二次打印是通过试错法。 (今天是 Python 的第一天)
- 第三个打印是参考this answer添加的。
令人惊讶的是,当前输出是
x is now : 33.0
<type 'float'>
float
我期待
x is now : 33
<type 'int'>
int
我没主意了。我错过了什么?
P.S。对于任何感兴趣的人,LIVE VERSION
在 python 2.x 中,round
总是 returns 一个浮点数。
根据打印语句的语法判断,您在 python 2.x.
而不是使用 round...!试试这个,因为 round 函数是对浮点值进行舍入..
然而,round 和类型转换为 int 都做同样的工作 @ background
希望这对您有所帮助..!!
x = int(32.7)
print 'x is now :',x
print str(type(x))
print type(x).__name__
或
y=32.7
x=int(y)
print 'x is now :',x
print str(type(x))
print type(x).__name__