python - 四舍五入浮点小数
问题描述
我正在尝试将我的输出四舍五入到小数点后两位。我知道这已经得到了回答,但我已经阅读了论坛并且已经坚持了一段时间。
我已经尝试在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)))
解决方案
你可以到这里:
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)}")
推荐阅读
- excel - Excel 2013 删除具有特定文本的行而不留下空白行
- python - 通过 Twine 将 py 文件上传到代理服务器时出现 SSL 错误
- apache-kafka - 使用 Spark 流将 Kafka Avro 序列化数据存储到镶木地板文件
- php - 提交按钮不在请求包中
- python - 从系列中删除分钟和小时
- php - 如何使用搜索框引导程序处理下拉列表中的大数据
- gmail - 解码 Gmail API 下载的附件数据
- c++ - 重载 [] 运算符
- firebase - 如何根据用户属性、用户受众发送 Firebase 云消息传递通知
- jasper-reports - 不在新页面 Jasper 报告中打印边框列