如何解决Python中的舍入错误?

问题描述 投票:0回答:1

请看我下面写的代码。我不断得到浮点数的返回值而不是四舍五入的整数,我的返回值始终是 (26.234567901234566)

height = 1.8
weight = 85

heightint = float(height)
weightint = int(weight)

BMI = input(weightint / (heightint ** 2))

BMIint = round(BMI)
print(BMIint)

请帮助我解决我的语法以及我做错了什么。

python integer rounding
1个回答
0
投票

您的代码有一些错误。首先,您不应该像您那样使用

input()
函数。另外,身高和体重已经是整数,不需要在前两行之后更改它们。代码的改进版本如下所示:

# Receive input from the user
weight = float(input("Enter your weight in kilograms: "))
height = float(input("Enter your height in centimeters: "))

# Calculate the BMI
bmi = weight / ((height / 100) ** 2)

# Display the result to the user (rounded to the nearest integer)
print("Your Body Mass Index (BMI) is: ", round(bmi))

© www.soinside.com 2019 - 2024. All rights reserved.