Search code examples
cprintfscanfstdio

Why does scanf expect two numbers?


I want the program to get the user's height and weight then input that into the bmi formula then output the result.

The height question works fine but when you enter a number into the weight question and press enter, it just makes a new line. Once you enter another number, it sets that to bmi and prints that.

#include<stdio.h>

int main()
{
int h, w, bmi;

printf("What is your height (in inches)? ");
scanf("%d", &h);

printf("What is your weight? ");
scanf("%d", &w);

bmi = (w/(h*h))*703;
scanf("%d", &bmi);

printf("\t\tBMI\n");
printf("US: %d\n", bmi);
}

Solution

  • You are using int for all three variables. So when you divide w (weight) by square of h (height) then generally it would give the result 0.xxxxxx. But here you are storing this result in an integer variable, but it can't store that floating value. So it stores only 0 and then 0 is multiplied with 703 and that is of no use.

    And you have defined the main function of type int so it must return a value.

    Use this code instead

        #include<stdio.h>
    
        int main()
        {
          float h, w, bmi;
    
          printf("What is your height (in inches)? ");
          scanf("%f", &h);
    
          printf("What is your weight? ");
          scanf("%f", &w);
          bmi=((w/(h*h))*703);
    
          printf("US: %f\n", bmi);
          return 0;
        }