-2

My program asks a user to enter Height, Weight.
Calculated BMI gets printed.

My problem is the output. It is constantly Zero.

height:180

weight:65

Expected output: 20.1

Calculation logic is:

BMI = weight / height^2 (squared)

Where is my error?

My code below:

//declare variables
        int weight;
        int height;
        double BMI;

        Console.WriteLine("Please enter your weight:");
        weight = int.Parse(Console.ReadLine());//Get weight from keyboard

        Console.WriteLine("Please enter your height:");
        height = int.Parse(Console.ReadLine());//get height from keyboard

        BMI = Math.Sqrt(height);//Square the height
        
        BMI = weight / height;//SET BMI TO WEIGHT DIVIDED BY HEIGHT SQUARED

        //if the BMI is less than 25
        if (BMI < 25)     {
            Console.WriteLine("BMI =" + BMI + " Congratulations! your BMI is perfect!.");     }

        else if (BMI > 30)     {
            Console.WriteLine("BMI =" + BMI + " Be careful! risks could lead to obesity.");     }

        else     {
            Console.WriteLine("BMI =" + BMI + " Please consider seeing a doctor, as you are of high risk of obesity.");     }

output I get is:

0

greybeard
  • 2,249
  • 8
  • 30
  • 66
ninten
  • 13
  • 4

2 Answers2

1

Math.Sqrt(Double) Method is used to get the square root of a specified number.

To do exponentiation, we can use Math.Pow(Double, Double) Method.

Just call it like:

BMI = weight / (Math.Pow(height, 2));

BMI = Math.Sqrt(height);//Square the hieght

Besides, if you want to get the square of height, you need to define a new variable to store it.

int squarevalue = Math.Pow(height, 2)

Rather than saving it to variable BMI.

大陸北方網友
  • 3,696
  • 3
  • 12
  • 37
0

I - Declare and Initialize variables like so:

        //declare variables
        int weight = 0;
        int height = 0;
        double BMI = 0;
        Boolean conversion;

II - Use TryParse to accept user input:

            Console.WriteLine("Please enter your height:");
            conversion = int.TryParse(Console.ReadLine(), out height);

            Console.WriteLine("Please enter your weight:");
            conversion = int.TryParse(Console.ReadLine(), out weight);

III - Use try catch clause for DivideByZeroException as follows:

        try
        {
            BMI = Math.Round((weight / Math.Pow(height, 2))*10000,1);
        }   catch(DivideByZeroException myException)
        {
            Console.WriteLine("Divided by Zero", myException.Message);
        }

IV - You have an error in your logic. Here is my fix:

BMI = Math.Round((weight / Math.Pow(height, 2))*10000,1);
Ivan
  • 399
  • 2
  • 5
  • 18