Python Can';t将摄氏度转换为华氏度
这是我的密码:Python Can';t将摄氏度转换为华氏度,python,Python,这是我的密码: # 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' >>> Cel
# 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
看起来您想要:
fah_two = "%.2f" % fah
%
格式化操作符的结果是一个字符串,因此您不需要fah_string
,因为fah_two
已经是一个字符串。此外,我认为temp*9/5
应该是temp*9/5.0在进行数学运算之前将temp
转换为浮点值,或者对常量使用浮点值(Python不会自动将结果转换为浮点,除非操作中有浮点。(.2f)%fah
应该是什么意思?@PauloScardine:在Python 3中,/
始终是浮点除法(但是,不清楚OP使用的是Python 2还是Python 3)@GregHewgill:我没有意识到这一点,谢谢。如果temp
是一个float
,这并不重要,但如果有人将int
传递给函数,这可能会令人惊讶。在Python 3中,//code>总是浮点除法(但是,不清楚OP是使用Python 2还是Python 3)。
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