簡體   English   中英

浮點數在我的 C 程序中顯示不正確

[英]float number is not displaying correctly in my C program

我只是在 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;
}

結果顯示為 0。

我只需要它來顯示帶小數的數字(使用%f並使用int表示重量和高度)。

由於變量是整數,它正在執行 integer 算術,並返回 integer 結果。 使用%f打印 integer 會導致未定義的行為。

將其中一個變量轉換為浮點數以獲得浮點結果。

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

另外,您的公式錯誤,應該是weight/(height*height)

我想到了。 我剛用這個:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM