我正在参加一个免费的在线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
orC
, 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='')
您要切掉最后两个字符,而不仅仅是最后一个:
应该是:
这就解释了你的准确性问题:
因为切片是从末尾开始计算的,所以切片到
:-2
同时切割单元和最后一个数字:请注意,您的代码太长,而不是:
这里有一个快速而肮脏的方法。
这将从C>;F转换,您可以轻松地将其翻转过来。
相关问题 更多 >
编程相关推荐