我知道我可以在 python 中使用 round(<int>, -1)
舍入到最接近的 10 的倍数有没有办法在不使用这个内置函数的情况下做到这一点?
编辑:
感谢您的反馈! 使用 divmod() 的答案很有趣,因为我以前从未使用过 divmod。以防万一有人想在 CodingBat 上知道解决方案使用评论中建议的模数。以防万一有人感兴趣。
def round10(num):
mod = num % 10
num -= mod
if mod >= 5: num += 10
return num
最佳答案
除以10
,int
,乘以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/