这里是我的代码:不能摄氏转换为华氏
# 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