【问题标题】:round() returns different result depending on the number of argumentsround() 根据参数的数量返回不同的结果
【发布时间】:2020-01-25 21:42:19
【问题描述】:

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

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

它打印以下内容:

4
4.0

有什么区别?

【问题讨论】:

  • 两种情况下我都得到 4.0 (python 3.5)
  • @taras: 不,Python 3.5 中的round(4.1) 产生4,只有round(4.1, 0) 产生4.0。做三次检查你的 Python 版本。如果必须,请在 Python 内部使用 import sys; print(sys.version_info),因为您报告的行为特定于 Python 2round() function documentation for Python 3 明确涵盖了这种情况:如果ndigits 被省略或者是None它返回最接近的整数到它的输入。.
  • @MartijnPieters,感谢您指出这一点。显然,我使用 2.7 检查过它,以为我运行的是 3.5。

标签: python python-3.x rounding


【解决方案1】:

如果不指定第二个参数,则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

【讨论】:

  • 我不知道你可以在 round() 上使用负数。很高兴知道!
  • 嗯,这里答案中最重要的部分是Help 函数,因为这样任何人都可以得到答案等等。
  • 应该是小数点point而不是小数点place
【解决方案2】:

当您指定小数位数时,即使该数字为 0,您也正在调用返回浮点数的方法版本。所以得到这样的结果是正常的。

【讨论】:

  • 是的,非常简单。就像它在help(round) 中所说的那样,它“在使用一个参数调用时返回一个 int,否则与数字的类型相同。”
  • 可能想要链接到docs 并引用第一句话。
  • "返回浮点数的方法版本" 这里没有重载或返回类型,它只是一个if 语句检查args
【解决方案3】:

我认为值得一提的是,你不仅可以遇到round(int) 或round(float),还可以遇到例如:round(class 'numpy.float64')。在这种情况下,即使“省略了 ndigits 或 None”,round 也不会返回整数。 (就像内置函数文档说的那样),但是类 numpy.float64 的类型。我分析了代码示例并在 python 3.7.3 中遇到了 round(x) 打印“10.0”

【讨论】:

    【解决方案4】:

    Python 中的 round() 函数有两个参数:

    1. 数字 - 要四舍五入的数字
    2. 位数(可选)- 给定数字要四舍五入的位数。

    每当你使用第二个参数时,Python 会自动将返回值的数据类型转换为浮点数。如果不使用第二个可选参数,则数据类型仍为整数。

    因此,传入参数时为4.0,不传入时为4。

    【讨论】:

    • 这是不正确的。 “每当你使用第二个参数时,Python 会自动将返回值的数据类型转换为浮点数。”。请引用来源。在这种情况下,尝试引用来源将表明返回类型的行为与 Aniket 描述的一样(并引用 Help(round)
    猜你喜欢
    • 2014-07-07
    • 2020-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-06
    • 2012-09-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多