转换温度时出现错误结果

2024-09-30 02:34:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我在ubuntu 12.04上的python2.7解释器中得到了错误的结果。 我在一个在线解释器中试过这个代码,代码还可以。你知道吗

#print temperature

kindc = str(raw_input("Please type c for celsius or f for fareneit  "))
tempc = float(raw_input("please type the number of degrees you want to convert   "))

def result(kind,temp):
    if kind == "c":
        result1 = float((temp-32)*9/5)
        return result1
    else:
        result1 = float(5/9*(temp-32))
        return result1

print result(kindc,tempc)

Tags: 代码forinputrawreturntyperesultfloat
2条回答

您希望摄氏度到华氏度的转换为:

 result1 = float(temp)*9/5+32

在python2中,5/9使用底除法,因为两个操作数都是整数。通过使至少一个参数成为浮点来强制浮点除:

result1 = (5.0 / 9.0) * (temp - 32)

摄氏度转换很可能不会受到这种影响,因为(temp - 32) * 9结果很可能已经是一个浮动,但最好在这里保持一致:

result1 = (temp * 9.0 / 5.0) + 32

注意,这里需要使用正确的公式;在乘以五分之九后加上+ 32。在这里,两个公式都不需要将结果强制转换为float();输出已经是一个浮点值。你知道吗

如果您使用的是使用python3的在线Python解释器,那么您的代码就可以工作,因为/运算符不是真正的除法运算(总是导致浮点值)。也可能是口译员有:

from __future__ import division

将python2转换为python3行为的导入。你知道吗

最后的转换函数是:

def result(kind, temp):
    if kind == "c":
        result1 = (temp * 9.0 / 5.0) + 32
        return result1
    else:
        result1 = 5.0 / 9.0 * (temp - 32)
        return result1

相关问题 更多 >

    热门问题