gpt4 book ai didi

python - python的温度转换

转载 作者:行者123 更新时间:2023-11-28 20:07:11 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com