首页 > 解决方案 > 四舍五入浮点小数

问题描述

我正在尝试将我的输出四舍五入到小数点后两位。我知道这已经得到了回答,但我已经阅读了论坛并且已经坚持了一段时间。

我已经尝试在round()内部使用该函数print(),甚至将其用作自己的变量。我在 Replit 上使用 Python 3.8.2。

height = input("enter your height in meters: ")
weight = input("enter your weight in kg: ")
height1 = float(height)
weight1 = float(weight)
results = float(weight1 / height1 ** 2)
results1 = str(results)
print("Your BMI: " + (round(results1, 2)))

标签: python

解决方案


你可以到这里:

height = input("enter your height in meters: ")
weight = input("enter your weight in kg: ")
height1 = float(height)
weight1 = float(weight)
results = float(weight1 / height1 ** 2)

但是下一行将结果变成了一个字符串(大概是为了能够将它与打印中的另一个字符串连接起来)。

你想在那之前把它四舍五入:

results = round(results, 2)
results = str(results)
print("Your BMI: " + results)

请注意,您也不需要重命名变量,只需覆盖它即可。

但是,实现相同的更简单的方法:

print(f"Your BMI: {round(results, 2)}")

字符串前面的告诉现代版本的 Python用你放在那里的表达式的值f替换花括号中的任何内容。{}

另请注意float(),即使表达式的结果已经是浮点数,您也会继续将结果转换为 。

脚本的更简洁(并且可以说更好)的版本:

height = float(input("enter your height in meters: "))
weight = float(input("enter your weight in kg: "))
result = weight / height ** 2
print(f"Your BMI: {round(result, 2)}")

推荐阅读