我是 Python 的新手,但对学习非常感兴趣。对于 uni Python 类(class),我将创建一个程序,将温度转换为摄氏度或华氏度,并将转换显示到小数点后第一位。我的问题出在打印行上。
如您在我的代码中所见,我尝试在连接时使用 round() 函数。虽然我试图将 float 转换为 str(),但当我运行我的程序时,出现以下错误。
TypeError: 类型 str 没有定义 round 方法
下一行
print (round(str(temp), 1)+ "摄氏度 = "+ str(degF) + "华氏度。")
我的 elif block 中的打印行也类似。 任何帮助理解和解决问题的帮助将不胜感激。
temp=float(input("Enter a temperature value to convert: "))
unit=str(input("Convert to Fahrenheit or Celsius? Enter f or c: "))
if unit=="c" or unit == "C":
degC=(temp)
temp=(1.8*temp)+32
print (round(str(temp), 1) + " degrees fahrenheit = " + str(degC) + " degrees Celsius. ")
elif unit=="f" or unit == "F":
degF=(temp)
temp=(temp-32)/1.8
print (round(str(temp), 1)+ " degrees celsius = " + str(degF) + " degrees Fahrenheit. ")
else:
print("you did not enter an f or c. Goodbye ")
我的输出应四舍五入到小数点后一位。
请您参考如下方法:
不要将 temp 转换为字符串。将其保留为 round 的 float 。将round后的结果转为str进行拼接
str(round(temp, 1))
