AhmadBenos
AhmadBenos

Reputation: 151

float number is not displaying correctly in my C program

I'm just trying out a BMI (body mass index) calculator in C, but I keep on getting 0 as the final answer. Here's the code:

#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;
}

It displays 0 as the result.

I just need it to display the number with decimals (using %f and using int for weight and height).

Upvotes: 0

Views: 393

Answers (2)

Barmar
Barmar

Reputation: 780663

Since the variables are integers, it's doing integer arithmetic, and returning an integer result. Printing an integer with %f causes undefined behavior.

Cast one of the variables to float to get a float result.

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

Also, you have the formula wrong, it should be weight/(height*height).

Upvotes: 5

AhmadBenos
AhmadBenos

Reputation: 151

i figured it out. i just used this:

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));

Upvotes: 0

Related Questions