Jonathan Vadil
Jonathan Vadil

Reputation: 1

BMI Calculator in C, Undeclared Identifiers

I'm trying to make a BMI calculator. I'm getting multiple "undeclared identifier" errors even though I've made them?

#include <stdio.h>

int main(void)
{//main method

    //Ex 2.32
    printf("Ex 2.32: Body Mass Index Calculator\n\n");

    int weightInPounds;
    int heightInInches;
    int bmi;

    //displays title
    printf("Body Mass Index Calculator\n");

    //user input for weight
    printf("Please input your weight in pounds:\n");
    scanf("%d", &weightInPounds);

    //user input for height
    printf("Please input your height in inches:\n");
    scanf("%d", &heightInInches);

    //caluclate BMI
    bmi = (weightInPounds * 703) / (heightInInches*heightInInches);
    printf("\n");   

    //display BMI categories
    printf("BMI Values\n");
    printf("Underweight: less than 18.5\n");
    printf("Normal: between 18.5 and 24.9\n");
    printf("Overweight: between 25 and 29.9\n");
    printf("Obese: 30 or greater\n\n");

    //display user BMI
    printf("Your BMI is: %d", &bmi);
    //end Ex 2.32

}//end main function

Upvotes: 0

Views: 189

Answers (3)

FatalError
FatalError

Reputation: 54621

With the information you've given, the most likely candidate is that your compiler is enforcing a C89 rule that requires all variable declarations to be placed at the start of a block. Take the following example:

#include <stdio.h>

int main (void)
{
  printf("Welcome to my program\n");

  int x = 5;
  printf("x = %d\n", x);

  return 0;
}

I can make gcc extra picky:

$ gcc -pedantic-errors -std=c89 -c vars.c
vars.c: In function ‘main’:
vars.c:7:3: error: ISO C90 forbids mixed declarations and code [-pedantic]

To fix this error, the variable declaration must be raised to the top of the block:

#include <stdio.h>

int main (void)
{
  int x = 5;

  printf("Welcome to my program\n");
  printf("x = %d\n", x);

  return 0;
}

And now it will build just fine that way. The fact that you see this behavior by default likely means you're using an old compiler (or possibly something specialized that only supports c89).

Upvotes: 0

Nicolas Charvoz
Nicolas Charvoz

Reputation: 1509

I tested your code and it works fine ! There are errors in the code such as :

printf("Your BMI is: %d", &bmi); 

You just have to print it like this :

printf("Your BMI is: %d", bmi);

Upvotes: 1

Igor Pejic
Igor Pejic

Reputation: 3698

Your compiler is old, it wants you to do something that is not really wrong, just how it was programmed some years ago.

Also you have a problem with your code: printf("Your BMI is: %d", &bmi);

Change it to:

printf("Your BMI is: %d", bmi);

Upvotes: 0

Related Questions