Opie-M - 3 months ago 21

C++ Question

This has been on my mind for a week now and i can't seem to understand it.

i have this problem:

`//1.Make an average of 3 numbers`

//2.Display average with two decimals exactly

//3.Average must NOT be rounded

#include <iostream>

#include <iomanip>

using namespace std;

int main()

{

double x, y ,z, average;

cin>> x >> y >> z;

average = (x+y+z)/3;

cout<<setprecision(2)<<fixed<< average;

return (0);

}

This is what i came up with but apparently it doesn't work 100%. (it rounds up the average sometimes)

Can anyone explain where it fails and how i can fix it?

Answer

It's a matter of definition and specification. The division `(x+y+z)/3`

is a floating-point one and `setprecision()`

obviously rounds the decimal digits, rather than truncates them. You may need to either choose another function (truncating, rather than rounding), or even partially employ a fixed-point logic. Eg if x, y and z are integers, you could use `((x+y+z)*100/3) / 100.0`

. (a quite common approach when 'amount' data are represented and processed).

OR (if x, y and z are floats):

```
floor((x+y+z)*100/3)/100
```