2012-08-02 61 views
-3

這裏是我的代碼:不能攝氏轉換爲華氏

# Note: Return a string of 2 decimal places. 
def Cel2Fah(temp): 
    fah = float((temp*9/5)+32) 
    fah_two = (%.2f) % fah 
    fah_string = str(fah_two) 
    return fah_string 

這是我應該得到什麼:

>>> Cel2Fah(28.0) 
    '82.40' 
>>> Cel2Fah(0.00) 
    '32.00' 

但我得到一個錯誤:

Traceback (most recent call last): 
File "Code", line 4 
fah_two = (%.2f) % fah 
^ 
SyntaxError: invalid syntax 

我不知道發生了什麼事...

這不似乎工作,要麼出於某種原因:

# Note: Return a string of 2 decimal places. 
def Cel2Fah(temp): 
    fah = temp*9/5+32 
    fah_cut = str(fah).split() 
    while len(fah_cut) > 4: 
     fah_cut.pop() 
    fah_shorter = fah_cut 
    return fah_shorter 
+0

轉換'temp'或使用常量浮動文字(Python將不會自動轉換結果漂浮除非在操作的浮動)。 – 2012-08-02 03:52:12

+0

'(%.2f)%fah'應該是什麼意思? – 2012-08-02 03:52:14

+1

@PauloScardine:在Python 3中,'/'總是浮點除法(但是,目前還不清楚OP是使用Python 2還是Python 3)。 – 2012-08-02 03:53:21

回答

0
sucmac:~ ajung$ cat x.py 
def toF(cel): 
    return '%.2f' % (cel * 1.8 +32) 

print toF(0) 
print toF(50) 
print toF(100) 

sucmac:~ ajung$ python x.py 
32.00 
122.00 
212.00 
4

它看起來像你想:

fah_two = "%.2f" % fah 

%格式化操作的結果是一個字符串,所以你不需要fah_string因爲fah_two已經一個字符串。

0

此外,我認爲temp * 9/5應該是temp * 9/5.0。浮動做數學之前

+0

如果'temp'是一個'float',就好像是這種情況,這並不重要,但是如果有人將一個'int'傳遞給函數,這可能會令人驚訝。 – 2012-08-02 04:16:15

+0

在Python 3中,'/'總是浮點除法(但是,目前還不清楚OP是使用Python 2還是Python 3)。 – 2012-08-02 04:17:48