Python 将浮点舍入为单个小数(具体问题)
我对Python非常陌生,但对学习非常感兴趣。对于uni Python课程,我将创建一个程序,将温度转换为摄氏度或华氏度,并将转换显示为第一个小数点。我的问题在于我的印刷行 正如您在我的代码中看到的,我尝试在连接时使用round()函数。尽管我试图将可能是浮点的值转换为str(),但当我运行程序时,我遇到了以下错误 TypeError:类型str未定义取整方法 下一行 打印(圆形(str(temp),1)+“摄氏度=“+str(degF)+”华氏度。”) 同样,对于我的elif集团中的打印行。 任何有助于理解和解决这个问题的人都将不胜感激Python 将浮点舍入为单个小数(具体问题),python,python-3.x,Python,Python 3.x,我对Python非常陌生,但对学习非常感兴趣。对于uni Python课程,我将创建一个程序,将温度转换为摄氏度或华氏度,并将转换显示为第一个小数点。我的问题在于我的印刷行 正如您在我的代码中看到的,我尝试在连接时使用round()函数。尽管我试图将可能是浮点的值转换为str(),但当我运行程序时,我遇到了以下错误 TypeError:类型str未定义取整方法 下一行 打印(圆形(str(temp),1)+“摄氏度=“+str(degF)+”华氏度。”) 同样,对于我的elif集团中的打印行。
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
后的结果转换为str
进行串联
str(round(temp, 1))
你的行动顺序不对。首先取整,然后转换为字符串:
print (str(round(temp), 1)+ " degrees celsius = " ...
除非这是一个课堂作业,使用round函数,否则我认为不需要round函数
print ("%.1f degrees Celsius = %.1f degrees Fahrenheit" % (temp, degC))
如果将temp保留为float,则无法与以下字符串语句连接