【问题标题】:Python: I have to round twice for it to workPython:我必须四舍五入才能工作
【发布时间】:2021-09-08 19:00:27
【问题描述】:

我正在学习 Python,但遇到了一个小问题,可能是语法问题,但四舍五入并没有按我的意愿工作。我想要四舍五入值的总和(a, b, c)。 对于我得到的视觉效果:https://imgur.com/5YP88L1 首先我创建:

def round10(num):
   return 10 * round(num/10)

然后:

def round_sum(a, b, c):
    return int(round10(a) + round10(b) + round10(c))

但是检查一下,round10(a) 如果“a”为 16,则给出 10 而不是 20,但是如果我将其更改为:

def round10(num):
    return 10 * round(round(num)/10)

然后如果 a 或 num 为 16,我想给出 20。

对不起,如果它太简单了,但我不明白为什么我需要将它四舍五入才能使它工作。

【问题讨论】:

  • 第一个函数(round10)工作正常
  • 10 * round(16 / 10) 在此处生成20。你确定10 是你得到的吗?
  • 也许您可以提供一些示例输入和您的预期/实际输出,以便其他人知道您卡在哪里?
  • 得到了 20 个 round10
  • 这可能是版本问题。在 Python 2.7 中,等式 16/10 产生整数 1,因为整数除法是整数除法。在 Python 3.x 中,情况不再如此(这就是其他评论者感到困惑的原因)。如果你想让它在 2.7 中工作,请将其中一个数字转换为浮点数:return 10 * round(num/10.0)。然后,您会得到准确的结果。

标签: python rounding python-2.x


【解决方案1】:

我检查了您的代码,使用 round10() 一次完全没问题。您可能应该检查 python 版本并尝试重新安装 python。

def round10(num):
   return 10 * round(num/10)

a = 10.234
b = 16
c = 11.32

def round_sum(a, b, c):
  return int(round10(a) + round10(b) + round10(c))

round_sum(a,b,c)

round10(16)

【讨论】:

  • 您认为重新安装 Python 会有什么帮助?
  • 这可能是一个错误或版本问题,重新安装应该可以通过重新配置来解决这个问题。
猜你喜欢
  • 2011-12-04
  • 1970-01-01
  • 2020-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-12
  • 2018-09-14
  • 1970-01-01
相关资源
最近更新 更多