【问题标题】:Rounding to the nearest Integer [duplicate]四舍五入到最接近的整数[重复]
【发布时间】:2015-11-17 09:07:40
【问题描述】:

如果与最接近的整数的绝对差小于或等于0.01,我想四舍五入到最接近的整数,

我的代码在测试中:

import unittest

def round_price(price):

  if abs(price - round(price)) <= 0.01:
    price = int(round(price))
  return price


class TestRounding(unittest.TestCase):
  def test_rounding(self):
    self.assertEqual(round_price(15.98), 15.98)
    self.assertEqual(round_price(15.99), 16)
    self.assertEqual(round_price(16.00), 16)
    self.assertEqual(round_price(16.01), 16)
    self.assertEqual(round_price(16.02), 16.02)

if __name__ == '__main__':
unittest.main()

测试的时候还是报错,

self.assertEqual(round_price(16.01), 16) AssertionError: 16.01 != 16

【问题讨论】:

  • 检查你的 if 子句。也许你想检查原始价格和四舍五入价格之间的绝对差。
  • 您可以通过说出测试时遇到的 what 错误来改进您的问题。会发生什么,您期望会发生什么?
  • 如果 price 是 2.993,你对 if abs(round(price)) &lt;= 0.01 有什么期望?
  • 我用测试和测试结果更新了我的问题,请检查

标签: python math rounding


【解决方案1】:

您需要比较价格和四舍五入价格之间的差异:

def round_price(price):

  if abs(price - round(price)) <= 0.01:
    price = int(round(price))
  return price

【讨论】:

  • 我试过了,还是一样的错误,我用测试更新了我的问题,你能检查一下吗?
  • 这是一个使用浮点数的特性,比如你和&lt;= 0.010000000001相比,它可能会通过。
  • 您更新的代码仍然错误...您的if 语句中需要abs(price - round(price)) 而不是abs(round(price))
  • 你说得对,马丁现在正在工作
【解决方案2】:
def round_price(price):

    if abs(price - round(price)) <= 0.01000001:
        price = round(price)
    return price

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-21
    • 2014-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多