python的温度转换

2024-04-20 05:00:59 发布

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

我正在参加一个免费的在线Python教程,它希望我:

Create a temperature converter which will convert Fahrenheit values to Celsius and vice-versa using the following two formulas which relate the temperature f in Fahrenheit to the temperature c in Celsius:

    f = c *  9/5 + 32
    c = (f -32)* 5/9 

The input will be a string consisting of a floating-point number followed immediately by the letter F or C, such as "13.2C". I need to convert to the other temperature scale and print the converted value in the same format. For example, if the input is "8F" then the output should be (approximately) "-13.333C", and if the input is "12.5C" then the output should be "54.5F".

我的答案总是有点离谱。例如,当正确的输出是-16.394444444444442C时,我得到-16.444444444444446C。我使用float有问题吗?我的代码如下:

def celsiusCon(farenheit):
   return (farenheit - 32)*(5/9)
def farenheitCon(celsius):
   return ((celsius*(9/5)) + 32)

inputStr = input()
inputDig = float(inputStr[0:-2])
if inputStr[-1] == 'C':
   celsius = inputDig
   print(farenheitCon(celsius),'F',sep ='')
if inputStr[-1] == 'F':
   farenheit = inputDig
   print(celsiusCon(farenheit),'C', sep='')

Tags: andthetoinwhichinputifbe
3条回答

您要切掉最后两个字符,而不仅仅是最后一个:

inputDig = float(inputStr[0:-2])

应该是:

inputDig = float(inputStr[0:-1])

这就解释了你的准确性问题:

>>> celsiusCon(2.4)
-16.444444444444446
>>> celsiusCon(2.49)
-16.394444444444446

因为切片是从末尾开始计算的,所以切片到:-2同时切割单元和最后一个数字:

>>> '2.49F'[:-2]
'2.4'
>>> '2.49F'[:-1]
'2.49'

请注意,您的代码太长,而不是:

tempInit = input()
temp = float(tempInit[:-1])
if tempInit[-1]== 'F':
    c=(temp-32)*5/9
    print(str(c)+'C')
if tempInit[-1]== 'C':
    f =(temp*9/5)+32
    print(str(f)+'F')

这里有一个快速而肮脏的方法。

temp = float(input("What's the temperature? C > F")))

conversion = (temp*9/5)+32

print(conversion)

这将从C>;F转换,您可以轻松地将其翻转过来。

相关问题 更多 >