我的脚本有问题,它在舍入代码中翻倍,我找不到错误。我似乎找不到问题是从哪里产生的。任何反馈将不胜感激。
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
假设您正在尝试四舍五入到最接近的1/4,用数字来做要容易得多(也更准确),而不是乱搞字符串。
import math
result_time = math.floor(4*first_time + .5) / 4
Floor()截断为负无穷大,因此即使first_time是负数,这种方法也可以工作。