I have the following calculation:
double a = 141150, b = 141270, c = 141410;
double d = (a + b + c) / 3;
cout << d << endl;
The output shows d = 141277
, whereas d
should be 141276.66666666...
. The calculation consists of double additions and a double division. Why am I getting a result that is rounded up?? By the way d = (a + b + c) / 3.0
doesn't help.
However in another similar calculation, the result is correct:
double u = 1, v = 2, x = 3, y = 4;
double z = (u + v + x + y) / 4;
z results in 2.5
as expected. These two calculations are essentially the same, but why different behaviors?
Lastly, I know C++ automatically truncates numbers casted to lower precision, but I've never heard of automatic rounding. Can someone shed some light?
Aucun commentaire:
Enregistrer un commentaire