在 python 3.7.5 下,我执行以下代码并得到一个奇怪的输出
for i in range(10):
print(round(i+0.5))
如果我理解正确的话,任何看起来像 xxx...x.5
的数字任意数字 x
应始终四舍五入为 xxx...x+1
下round()
运算,无论完整整数部分是偶数还是奇数。我的输入是否犯了一些错误?如何解决这个问题?感谢您的任何建议!
最佳答案
最好使用math
模块:
根据需要将 round
替换为 floor
或 ceil
:
from math import floor, ceil
现在对于向下舍入使用floor()
,对于向上舍入使用ceil()
print(floor(2.9))
output: 2
print(ceil(1.1))
output: 2
关于python3.7.5 : round() behaves differently in seemingly equivalent cases?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58830587/