2012-08-02 96 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