Why do these functions truncate the return value?

291 views Asked by At

Beware there be Homework below.

Edits:

Took out useless information.

So obviously this is a homework assignment everything seems correct besides the calculations inside my functions.

How do I return a non truncated value?

float hat(float weight, float height) {
    return (weight/height)*2.9;
}
float jacket(float weight, float height, int age) {
    double result = (height * weight) / 288;
    /*now for every 10 years past 30 add (1/8) to the result*/
    if((age - 30) > 0){
        int temp = (age - 30) / 10;
        result = result + (temp * .125);
        //cout<<"result is: "<<result<<endl;
    }
    return result;
}

float waist(float weight, int age) {
    double result = weight / 5.7;
    /*now for every 2 years past 28 we add (1/10) to the result*/
    if((age - 28) > 0){
        int temp = (age - 28) / 2;
        result = result + (temp * .1);
    }
return result;}
2

There are 2 answers

0
Ely On BEST ANSWER

Set fixed:

  // Output data //
  cout << fixed;
  cout << "hat size: " << setprecision(2) << hat(weight, height) << endl;
  cout << "jacket size: " << setprecision(2) << jacket(weight, height, age) << endl;
  cout << "waist size: " << setprecision(2) << waist(weight, age) << endl;
0
zwol On
cout << "hat size: " << setprecision(2) << hat(weight, height) << endl;

You've tripped over a gotcha in the way iostreams formatted output works.

In the "default" mode for formatting floating point values (not having requested fixed or scientific output), the precision is the total number of digits to print, on both sides of the decimal point. Think "significant figures", not "number of fractional digits".

For what you are trying to do, I suggest you either use "fixed" mode or round by hand and then don't specify a precision.