【问题标题】:simplest way to convert either a float or an int to the nearest integer in Python在 Python 中将浮点数或整数转换为最接近的整数的最简单方法
【发布时间】:2014-07-18 23:04:16
【问题描述】:

我想定义一个函数,它可以将整数或浮点数作为参数,并返回最接近的整数(即,如果输入参数本身已经是整数)。我试过这个:

 def toNearestInt(x):
    return int(x+0.5)

但它不适用于负整数。

>>> toNearestInt(3)
3
>>> toNearestInt(3.0)
3
>>> toNearestInt(3.49)
3
>>> toNearestInt(3.50)
4
>>> toNearestInt(-3)
-2

我该如何解决?

【问题讨论】:

    标签: python math type-conversion


    【解决方案1】:

    Python 已经有一个内置函数(或多或少)。

    >>> round(-3, 0)
    -3.0
    >>> round(-3.5, 0)
    -4.0
    >>> round(-3.4, 0)
    -3.0
    >>> round(-4.5, 0)
    -5.0
    >>> round(4.5, 0)
    5.0
    

    当然,您可能希望将其封装在对 int 的调用中...

    def toNearestInt(x):
        return int(round(x, 0))
    

    【讨论】:

    • 我想我尝试了 round(),但是对于 0.5 边界,它总是从零开始四舍五入,例如回合(0.5)= 1.0,回合(1.5)= 2.0,回合(-0.5)= -1.0,回合(-1.5)= -2.0
    • @JasonS -- 当它与任一值的距离相等时,您所做的任何选择都将是任意的......
    • 不是任意的。有多种技术:en.wikipedia.org/wiki/Rounding#Tie-breaking 但你是对的,这是一种选择。
    • 无论如何,除非我在做一些挑剔的统计工作,是的,这并不重要,所以为了简单起见,我会采用你的方法。
    • @JasonS:如果打破平局的方案确实很重要,您还应该注意 Python 2 和 Python 3 之间的行为 changed
    【解决方案2】:

    您可以在此处保留您的初始方法,只需检查输入是否为负数,在这种情况下添加 -0.5。

    def toNearestInt(x):
        a = 0.5
        if x < 0:
            a*=-1
        return int(x+a)
    

    【讨论】:

      猜你喜欢
      • 2011-03-24
      • 1970-01-01
      • 2013-06-03
      • 1970-01-01
      • 2022-09-27
      • 2010-09-12
      • 1970-01-01
      • 2012-09-18
      相关资源
      最近更新 更多