浮点数在我的 C 程序中没有正确显示

Ahm*_*nos 0 c

我只是在用 C 语言尝试一个 BMI(体重指数)计算器,但我一直得到 0 作为最终答案。这是代码:

#include <stdio.h>

int main(){

    int weight, height;
    printf("Enter your weight in kilograms: ");
    scanf("%d", &weight);
    printf("Enter your height in meters: ");
    scanf("%d", &height);
    printf("Your BMI(body's mass index) is %f\n", weight/height*height);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

结果显示为 0。

我只需要它来显示带小数的数字(使用%f和使用int体重和身高)。

Bar*_*mar 5

由于变量是整数,它进行整数运算,并返回整数结果。打印一个整数并%f导致未定义的行为。

将变量之一转换为 float 以获得浮动结果。

printf("Your BMI(body's mass index) is %f\n", (float)weight/(height*height));

Run Code Online (Sandbox Code Playgroud)

另外,你的公式错了,应该是weight/(height*height)