0

I run this code but the output was different from what I expected. The output:

c = 1324
v = 1324.99

I expected that the output should be 1324.987 for v. Why is the data in v different from output?

I'm using code lite on Windows 8 32.

#include <iostream>
using namespace std;
int main()
{
    double v = 1324.987;
    int n;
    n = int (v);
    cout << "c = " << n << endl;
    cout << "v = " << v << endl;
    return 0;
}
phuclv
  • 37,963
  • 15
  • 156
  • 475
CatCoder
  • 248
  • 2
  • 10

2 Answers2

4

Floating point types inherit rounding errors as a result of their fixed width representations. For more information, see What Every Computer Scientist Should Know About Floating-Point Arithmetic.

autistic
  • 1
  • 3
  • 35
  • 80
  • 2
    while useful information, that's not what is going on here; in fact the default precision for display is 6. The output would be 1324.99 even if there were no rounding errors. `double` has more than enough precision to store 1324.987. – M.M Jun 20 '15 at 13:01
3

The default precision when printing with cout is 6, so only 6 decimal places will be displayed. The number is rounded to the nearest value, that's why you saw 1324.99. You need to set a higher precision to see the more "correct" value

However, setting the precision too high may print out a lot of garbage digits behind, because binary floating-point types cannot store all decimal floating-point values exactly.

phuclv
  • 37,963
  • 15
  • 156
  • 475