gpt4 book ai didi

python - round() 根据参数的数量返回不同的结果

转载 作者:IT老高 更新时间:2023-10-28 21:47:34 27 4
gpt4 key购买 nike

在使用 round() 函数时,我注意到我得到了两个不同的结果,这取决于我是没有明确选择要包含的小数位数还是选择数字为 0。

x = 4.1
print(round(x))
print(round(x, 0))

它打印以下内容:

4
4.0

有什么区别?

最佳答案

如果不指定第二个参数,则round函数返回一个整数,否则返回值与第一个参数的类型相同:

>>> help(round)
Help on built-in function round in module builtins:

round(number, ndigits=None)
Round a number to a given precision in decimal digits.

The return value is an integer if ndigits is omitted or None. Otherwise
the return value has the same type as the number. ndigits may be negative.

所以如果传递的参数是整数和零,则返回值将是整数类型:

>>> round(100, 0)
100
>>> round(100, 1)
100

为了完整起见:

负数用于小数点前四舍五入

>>> round(124638, -2)
124600
>>> round(15432.346, -2)
15400.0

关于python - round() 根据参数的数量返回不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52893372/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com