我的脚本出现问题,它在舍入代码中加倍,我无法找到错误。我似乎无法找到问题产生的地方。对于任何反馈,我们都表示感谢。
def research_rounding(first_time):
first_time = float(first_time)
if first_time == 0: #If time is 0, return 0
result_time = 0
return result_time
else: #If time is not 0, continue rounding func
first_time = str(first_time)
find_dec = "."
length = len(first_time)
found_dec = (first_time.find(find_dec))
found_whole = float(first_time[0:found_dec])
found_tenth = float(first_time[found_dec:length])
if found_tenth < 0.25 and found_whole >= 1 and found_tenth != 0:
result_time = 0.25 + found_whole
return result_time
elif found_tenth == 0 and found_whole >=1:
result_time = 0 + found_whole
return result_time
elif found_tenth == 0 and found_whole == 0:
result_time = 0
return result_time
elif found_tenth <= 0.5:
result_time = 0.5 + found_whole
return result_time
elif found_tenth > 0.5 and found_tenth < 0.75:
result_time = 0.75 + found_whole
return result_time
elif found_tenth > 0.75 and found_tenth < 1:
result_time = 1 + found_whole
return result_time
else:
pass
答案 0 :(得分:1)
假设你想要四舍五入到最接近的1/4,那么用数字方法做得更容易(也更准确),而不是乱用字符串。
import math
result_time = math.floor(4*first_time + .5) / 4
Floor()截断为负无穷大,因此即使first_time为负数,此方法也能正常工作。