2013-03-08 61 views
3
# Fahrenheit to Celcius  
def f2c(): 
    userInput = tempEntry.get().lower() 
    thisEquation = "Fahrenheit to Celcius" 
    if userInput == "": 
     textWid.insert(END,"-- " + thisEquation + " --") 
     textWid.insert(END,"\n") 
     textWid.insert(END,temp_equations[thisEquation]) 
     textWid.insert(END,"\n") 
     textWid.insert(END,"\n") 
    elif userInput.isdigit(): 
     textWid.insert(END,"Fahrenheit = ") 
     textWid.insert(END,str(((float(userInput) - 32) * (5/9)))) 
     textWid.insert(END,"\n") 
    else: 
     textWid.insert(END,"Invalid entry for"+" "+thisEquation) 
     textWid.insert(END,"\n") 

# Fahrenheit to Kelvin 
def f2k(): 
    userInput = tempEntry.get().lower() 
    thisEquation = "Fahrenheit to Kelvin" 
    if userInput == "": 
     textWid.insert(END,"-- " + thisEquation + " --") 
     textWid.insert(END,"\n") 
     textWid.insert(END,temp_equations[thisEquation]) 
     textWid.insert(END,"\n") 
     textWid.insert(END,"\n") 
    elif userInput.isdigit(): 
     textWid.insert(END,"Fahrenheit = ") 
     textWid.insert(END,str(((5/9)*(float(userInput) - 32) + 273.15))) 
     textWid.insert(END,"\n") 
    else: 
     textWid.insert(END,"Invalid entry for"+" "+thisEquation) 
     textWid.insert(END,"\n") 

userInput是全局定義的Tkinter輸入框。 我強烈懷疑我的問題源於兩個方程式,但我已經嘗試了多次重複使用它們。使用我的華氏溫度到Celcius/Kelvin轉換器時遇到問題

我的華氏溫度到攝氏轉換器總是返回0.0 華氏溫度到開爾文轉換器每次約20次關閉。

在這裏完全難倒傢伙,任何幫助將不勝感激。

回答

8

5/9是您的問題:

>>> 5/9 
    0 

在Python 2,劃分的整數一個整數得到的整數。你想讓至少一個數字浮動:

>>> 5.0/9 
    0.5555555555555556 
>>> 5.0/9.0 
    0.5555555555555556 
+2

或者兩個數字!我會把'5.0/9.0'只是爲了讓人類和Python都清楚它。 – steveha 2013-03-08 01:21:49

+1

+1。你也可以通過刪除括號來解決這個問題:'(float(userInput) - 32)* 5/9'將'float'乘以'int',返回'float',然後再除以int,再次返回'float'。 – abarnert 2013-03-08 01:22:22

+3

或'from __future__ import division'在這種情況下是可行的... – 2013-03-08 01:22:24