python - python的温度转换

标签 python python-3.x decimal floating-point-precision

我正在学习免费的在线 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='')

最佳答案

您正在切断最后的两个 个字符,而不仅仅是最后一个:

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'

关于python - python的温度转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18780440/

相关文章:

c# - 百分比值的小数格式?

Python tox 依赖项安装输出

python - BeautifulSoup | python | URL循环

python - Pandas - 将一组列分箱并对另一列求和

python - 有没有办法在函数外部从已部署的 Google Cloud Function 导入 python 帮助程序库?

java - 数学技能较弱 : What is an 8-bit numerator and 8-bit denominator?

mysql - 更改MySQL中所有表的小数位数

python - 向 Pandas DataFrame 添加一个新列,并使用来自单独 DataFrame 的编码数据而不使用循环?

python - 如何在 Python 正则表达式中匹配重复后的非字符

python - 根据累积值将非累积计算到新列中 (Python)