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

标签 python python-3.x

对于一门类(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/

相关文章:

python - 可以直接在action.yml文件的 "run | "段下写Python代码吗

python - Tensorflow 无法处理惯用的简单代码

python-3.x - 基于函数计算 nxn 距离矩阵

python-3.x - 如何在 Tensorflow 2.0 中使用嵌入投影仪

python - 获取列表中所有元素的增量计数

python - 无法在 ubuntu 服务器 18.04 aws 上安装 tensorflow

python - pdfkit 页眉和页脚

python - 如何在 Python - GEKKO 中构建和打印循环生成的优化值列表?

python - 使用 PyQt 实现分割器(QtCreator 生成的文件)

python os.system 似乎无缘无故挂起