2015-11-05 52 views
0

我正在做華氏四捨五入整數批量轉換爲攝氏(是的,對於codeabbey.com),我花了幾個小時就陷入了一些看起來應該流暢運行的東西。具體來說,我的結果都是零。因此在for循環中的某處,可能在jk的分配中,數學正在崩潰。我一遍又一遍地看了一遍。爲什麼我在結果中得到零值?爲什麼我所有的結果都是0?

fahrenheit = raw_input().split() # Dump copy-and-pasted values into a list. 
iter = int(fahrenheit.pop(0)) # Remove the first value and use it as a counter. 

celsius = [] # Make an empty list for results. 
x = 0 # Index counter 

for i in fahrenheit: 
    j = (int(i)-32) * (5.0/9) 
    k = (int(i)-32) * (5/9) 
    if float(j) == k: 
     celsius.append(j) 
    elif j > 0: # For positive results 
     if (j - k) >= 0.5: # If integer value needs +1 to round up. 
      celsius.append(k+1) 
     else: 
      celsius.append(k) 
    elif j < 0: # For negative results 
     if (k - j) >= 0.5: 
      celsius.append(k+1) # If integer values needs +1 to bring it closer to 0. 
     else: 
      celsius.append(k) 
    else: 
     celsius.append(k) # If the result is 0. 

print ' '.join(celsius) 

該奇怪設置的數據調用格式。數據中的第一個數字不是要測試的溫度。所有其他人都是。所以5 80 -3 32 212 71要求五個計算:80,-3,32,212和71轉換爲攝氏。

+6

整數除法:'5/9 == 0' –

+1

...... D'哦!我不敢相信我看了那麼久,從未意識到這一點。感謝您指出我! – thektulu7

+0

您可以通過刪除「5/9」附近的括號來獲得正確的結果。沒有它們,乘以5就會在分割之前發生。 – Blckknght

回答

1

正如彼得伍德在他的評論中指出的,由於整數除法,5/9評估爲0。但是,通過使用內置的round函數,可以簡化程序的其餘部分。

>>> [round(x) for x in [26.0, 26.4, 26.5, 26.9]] 
[26.0, 26.0, 27.0, 27.0] 

然後,您可以重寫,如:

celsius = [int(round((f-32)*5.0/9.0)) for f in fahrenheit[1:]] 
+0

方式很酷。謝謝。我不能等到我學到足夠的東西,才能將我的代碼壓縮到這樣高效的行中。一定要保持插件'一點點! – thektulu7

相關問題