Float???Double???

I can't get my float to display decimals................What the hell! I know I'm passing a multi int's , but what the hell?



float averageValue(int a, int b, int x, int y, int z)
{float average;
average = ((a+b+x+y+z)/5);
cout.precision(2);
return average;
}
You didn't set the ios::fixed flag :
1
2
3
4
5
6
7
8
float averageValue(int a, int b, int x, int y, int z)
{
    float average;
    average = ( a + b + x + y + z ) / 5.0;
    cout.setf(ios::fixed);
    cout.precision(2);
    return average;
}
.

Just as a side note, you must divide by 5.0 and NOT by 5 to get the desired answer.
EDIT:
Reason: Since average is a float, the result of ( a + b + x + y + z ) / 5 will be converted to float only after the operations have been made. So, ( a + b + x + y + z ) will give an integer. And this integer when divided by 5, also gives an integer. So you lose the decimal part here. And remaining integer part is type-converted to float which will make anything after the decimal .00. Hope you get the idea.
Last edited on
Thank you........It all makes sense now.
Topic archived. No new replies allowed.