python - 在不使用 round() 的情况下在 python 中舍入整数

标签 python rounding

我知道我可以在 python 中使用 round(<int>, -1) 舍入到最接近的 10 的倍数有没有办法在不使用这个内置函数的情况下做到这一点?

编辑:

感谢您的反馈! 使用 divmod() 的答案很有趣,因为我以前从未使用过 divmod。以防万一有人想在 CodingBat 上知道解决方案使用评论中建议的模数。以防万一有人感兴趣。

def round10(num):
  mod = num % 10
  num -= mod
  if mod >= 5: num += 10
  return num

最佳答案

除以10int,乘以10

实际上,您可以在没有任何内置函数的情况下使用 // 运算符来完成此操作:

>>> def round(x):
...     return (x//10)*10
... 
>>> round(15.)
10.0
>>> round(25.)
20.0

当然,这总是向下舍入。如果您想对余数大于 5 的值进行四舍五入,您可以使用 divmod:

def round(x):
    n, remainder = divmod(x, 10)
    if remainder >= 5:
        n += 1
    return n * 10

关于python - 在不使用 round() 的情况下在 python 中舍入整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20789437/

相关文章:

python - 合并具有偏移量的数据帧行(同一天生成但具有不同的时间戳)

python - Django:基于 'as_view()' 方法的通用 View

python - 如何在python中将0.5四舍五入到最接近的整数?

javascript - 有没有办法在 Javascript 中 chop 科学记数法?

c# - 将时间值向下舍入到最接近的刻钟

C -printf 类型转换

python , Pandas : Cut off filter for spikes in a cumulative series

python - 初始化一个字典,其中每个项目都是空的唯一列表的列表

python - python中的嵌套列表和排序

.net - 使用 == 运算符比较两个舍入的 float 是否正确?