這裏是我的代碼:不能攝氏轉換爲華氏
# 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
轉換'temp'或使用常量浮動文字(Python將不會自動轉換結果漂浮除非在操作的浮動)。 – 2012-08-02 03:52:12
'(%.2f)%fah'應該是什麼意思? – 2012-08-02 03:52:14
@PauloScardine:在Python 3中,'/'總是浮點除法(但是,目前還不清楚OP是使用Python 2還是Python 3)。 – 2012-08-02 03:53:21