0

I'm writing a piece of code for a class, and part of it is to take an operation on integers and store it in a double (without any truncation). I'm trying to use the static_cast <double> (EXPRESSION GOES HERE); form, but it isn't working. When I output the new value, I get integers (but it does show the decimal because of the setprecision(2)). I get answers like 22.00, 35.00, etc. It's clearly truncating.

bmi = static_cast<double> (703 * weight / (height*height));

is the line in question. Full code below.

#include <iostream>
#include<iomanip>

using namespace std;

int main(){

        int height, weight;//delcare height and weight as integers
        double bmi; //bmi as a double

        {           
            cout << "BMI Values" << endl;                       //display the chart to begin
            cout << "Underweight     < 18.5" << endl;
            cout << "Normal          > 18.5 and < 25" << endl;
            cout << "Overweight      > 25   and < 30" << endl;
            cout << "Obese           > 30" << endl << endl;

            cout << "Enter height in inches: ";                   //get height and weight from user
            cin >> height;
            cout << endl << "Enter weight in pounds: ";
            cin >> weight;
        }

        bmi = static_cast<double> (703 * weight / (height*height)); //BMI calculation
        cout << fixed << showpoint << setprecision(2); //always show two decimal places

        cout << endl << "BMI = " << bmi;

        if (bmi < 18.5)  //if (underweight) -> display underweight, etc.
            cout << " Underweight" << endl;
        else if (bmi <= 25)
            cout << " Normal" << endl;
            else if (bmi <= 30)
                cout << " Overweight" << endl;
                else
                    cout << " Obese" << endl;

    cin.get(); cin.get();   //wait for user to read result
    return 0;
}

Edited by bobtherobot

2
Contributors
1
Reply
18
Views
2 Years
Discussion Span
Last Post by NathanOliver
0

To get a double one of the numbers needs to become a floating point number so the compiler knows to do floating point math.

bmi = static_cast<double> (703 * weight / (height*height)); //BMI calculation

becomes

bmi = 703.0 * weight / (height*height); //BMI calculation

As an FYI if none of your number a literals you can use c style cast you c++ cast to convert one of the number of the calculation to a double.

bmi = static_cast<double>(weight) / (height*height);
//or
bmi = (double)weight / (height*height);
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.