Help rounding double

I need help understanding why the round() function below provides two different results despite using it on doubles with the same values.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <cmath>

using namespace std;

int main()
{
    // works:
    double dd = 13.5;
    cout << "dd before round: " << dd << '\n';
    dd = round(dd);
    cout << "dd after round: " << dd << '\n';

    // does not work:
    int i = 10;
    double d = 10.135;
    d = d - i;
    cout << "d - i: " << d << '\n';
    d *= 100;
    cout << "d * 100: " << d << '\n'; // shows 13.5 before rounding
    d = round(d);
    cout << "d rounded: " << round(d); // but rounds down to 13
   
    return 0;
}
Last edited on
#$@^ computers, I'm done programming.

j/k. Thanks for the link. Looks dense, but probably something I need to eventually understand. I'll give it a read.

Is there a simpler explanation somewhere else for noobs like me?
Last edited on
well,
5 divided by 2 is 2.5

but if you ask a computer it might return you something like:
2.50000000000000001

and 25 divided by 10 might give you something else *slightly* different.

Take a look at these examples:
http://stackoverflow.com/questions/2100490/floating-point-inaccuracy-examples

This seems a good 'tutorial':
https://support.microsoft.com/en-us/kb/42980
Floating points are usually stored as x*(2^y). Many numbers that are finitely expressible in decimal, lie exactly between two binary numbers, such that adding more binary digits will not reach their exact value. Hence any one of the values which d was set to, may not have been represented exactly, but with a small error. This means that the value was probably just below 13.5 but when printing, the number of decimal places expected was too small for it to show this so it rounded. I think.
That makes sense. Thanks, both of you.
Topic archived. No new replies allowed.