<p>我正在参加一个免费的在线Python教程,它希望我:</p>
<blockquote>
<p>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:</p>
<pre><code> f = c * 9/5 + 32
c = (f -32)* 5/9
</code></pre>
<p>The input will be a string consisting of a floating-point number followed immediately by the letter <code>F</code> or <code>C</code>, such
as <code>"13.2C"</code>. 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) <code>"-13.333C"</code>, and if the
input is <code>"12.5C"</code> then the output should be <code>"54.5F"</code>.</p>
</blockquote>
<p>我的答案总是有点离谱。例如,当正确的输出是<code>-16.394444444444442C</code>时,我得到<code>-16.444444444444446C</code>。我使用float有问题吗?我的代码如下:</p>
<pre><code>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='')
</code></pre>