我在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)
您希望摄氏度到华氏度的转换为:
在python2中,
5/9
使用底除法,因为两个操作数都是整数。通过使至少一个参数成为浮点来强制浮点除:摄氏度转换很可能不会受到这种影响,因为
(temp - 32) * 9
结果很可能已经是一个浮动,但最好在这里保持一致:注意,这里需要使用正确的公式;在乘以五分之九后加上
+ 32
。在这里,两个公式都不需要将结果强制转换为float()
;输出已经是一个浮点值。你知道吗如果您使用的是使用python3的在线Python解释器,那么您的代码就可以工作,因为
/
运算符不是真正的除法运算(总是导致浮点值)。也可能是口译员有:将python2转换为python3行为的导入。你知道吗
最后的转换函数是:
相关问题 更多 >
编程相关推荐