2016-09-01 47 views
1

在我的腳本中存在一個問題,它在舍入代碼中翻倍並且找不到錯誤。我似乎無法找到問題產生的來源。對於任何反饋,我們都表示感謝。舍入代碼中的加倍錯誤

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 
+3

什麼問題?添加預期和當前結果的示例。 – Daniel

回答

1

假設你正試圖四捨五入到最接近的1/4,這是一個更容易(更準確)做數字,而不是用繩子亂搞。

import math 
result_time = math.floor(4*first_time + .5)/4 

Floor()截斷爲負無窮大,因此即使first_time爲負數,該方法也可以工作。