gpt4 book ai didi

python - 如何将 float 四舍五入到小数点后第一位?

转载 作者:行者123 更新时间:2023-12-01 01:13:49 26 4
gpt4 key购买 nike

对于一门类(class),我要编写一个程序,将华氏温度转换为摄氏度,反之亦然。结果应四舍五入至小数点后第一位。我已经通过多种方式尝试了“round”功能,但没有成功。

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(str(temp) + " degrees fahrenheit = " + str(degC) + " degrees Celsius. ")
if unit=="f" or unit == "F":
degF=(temp)
temp= (temp-32)/1.8
print(str(temp)+ " degrees celsius = " + str(degF) + " degrees Fahrenheit. ")
else:
print("you did not enter an f or c. Goodbye ")

最佳答案

您可以使用round(number, 1)内置函数!

例如:

>>> round(45.32345, 1)

45.3

就您而言:

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(str(round(temp), 1) + " degrees fahrenheit = " + str(degC) + " degrees Celsius. ")
el*emphasized text*if unit=="f" or unit == "F":
degF=(temp)
temp= (temp-32)/1.8
print(str(round(temp), 1)+ " degrees celsius = " + str(degF) + " degrees Fahrenheit. ")
else:
print("you did not enter an f or c. Goodbye ")

Python 实际上做的是这样的:

def truncate(n, decimals=0):
multiplier = 10 ** decimals
return int(n * multiplier) / multiplier

您可以阅读有关 python-rounding 的更多信息

希望这有帮助!

关于python - 如何将 float 四舍五入到小数点后第一位?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54578622/

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