项目场景:
在做(PAT)程序运行时间这道题时,发现一个奇怪的现象,python内置函数round居然不能准确的四舍五入,便深入了解了一下。
问题描述:
题目要求秒数采用四舍五入取值
这是我直接用round函数得到的结果
这是正确答案
很明显四舍五入出现了问题
以下是错误代码:
n = input().split()
temp = []
s = (int(n[1]) - int(n[0])) / 100
s = round(s)
second = s % 60
minute = s // 60 % 60
hour = s // 3600
print('{}:{}:{}'.format(str(hour).rjust(2, '0'), str(minute).rjust(2, '0'),
str(second).rjust(2, '0')))
原因分析:
int类型在Python中是动态长度的,理论上是支持无限大的数字,他们的浮点数在截断时会有一定的误差存在。
具体参考https://m.py.cn/faq/python/17167.html
解决方案:
n = input().split()
s = (int(n[1]) - int(n[0])) / 100
s = int(s + 0.5)
# s = round(s)
second = s % 60
minute = s // 60 % 60
hour = s // 3600
print('{}:{}:{}'.format(str(hour).rjust(2, '0'), str(minute).rjust(2, '0'),
str(second).rjust(2, '0')))
另外附上Python3的round()函数取舍规则https://blog.csdn.net/qq_53438188/article/details/123263346