2013-11-01 66 views
0

我已經試過在python中製作一個溫度轉換計算器。任何幫助什麼是錯的?我把20C,它告訴我,20c=52f,我知道這是不正確的。以下是代碼:溫度計算器不輸出正確的溫度?

def convert(changeto,temp): 
    if changeto == "c": 
     converted = (5/9)*(temp-32) 
     print '%d C = %d F' % (temp,converted) 
    elif changeto == "f": 
     converted = (9/5)*(temp+32) 
     print '%d F = %d C' % (temp, converted) 
    else: 
     print "Error, type C or F for Celsius or Fahrenheit conversions." 

print "Temperature Converter" 

temp = float(raw_input("Enter a temperature: ")) 
changeto = str(raw_input("Convert to (F)ahrenheit or (C)elsius? ")) 

convert(changeto,temp) 

raw_input("Any key to exit") 
+0

9/5始終是1 ....嘗試9/5.0而不是 –

+1

除了浮點錯位之外,在從C到f的相乘之前,還要加上32。它應該是'(9/5.0 * temp)+ 32'。 (或'9/5.',但我喜歡明確的'0'作爲提醒。)或者,如果你想整數數學(截斷任何小數部分),「((9 * temp)/ 5)+ 32」和'(5 *(temp - 32))/ 9'。 Parens補充說明。 –

+0

@PeterDeGlopper謝謝!這解決了它。我只是複製了我在一些python初學者問題網站上找到的公式,並沒有考慮他們的數學問題。懶惰在屁股裏再次咬住我,好啊。 – Ace

回答

3

根據您的Python版本,5/9可能計算結果爲零。將其更改爲5./9(點將5變成floating-point文字)。

其他部門也是如此。

最重要的是,你擁有的兩個公式不是相互顛倒的,需要重新檢查。