0

file.txt

123.56
89.78
8.89
468.98
567.90
5.78
178908.90
12.56
6789.90
12.56
16.780
0.00

I've parsed the numbers into an array called float A[150] = {0}. So, A looks like:

A[0] = 123.56
A[1] = 89.78
....
....
A[10] = 16.780
A[11] = 0.00
A[12] = 0
A[13] = 0
...
...

Then, I have a sorting Algorithm

Sort(A, i) // where i is the number of elements (12)

Now A[] looks like

A[0] = 0
A[1] = 5.78
...
...
A[10] = 6789.90
A[11] = 178908.90

Then, I write it to a file called "Final.txt"

std::ofstream File (Name);
if (File.is_open())
    {
        for (j = 0; j < i; j++)
        {
            File << A[j] << std::endl;
        }
    }

The file output "Final.txt" looks like:

0
5.78
8.89
12.56
12.56
16.78
89.78
123.56
468.98
567.9
6789.9
178909 // Why it is NOT CORRECT !!!!!!!

The problem with A[11] after the sorting, why is it not correct in "Final.txt", even though it is correct when I debug it in the A[11] ?

user3552818
  • 75
  • 1
  • 1
  • 7

2 Answers2

0

Floating point values are printed with several constraints to make the values readable. For instance you would probably not want the output of 16.78 to read

16.799999999999998

Which might well be a more correct representation of 16.78. To avoid that operator << operation on ostreams uses a precision field to determine how many significant digits to print. This value is obviously set too small for your application.

Reference http://en.cppreference.com/w/cpp/io/manip/setprecision.

Other formatting settings is given by the link πάντα ῥεῖ provided.

Captain Giraffe
  • 13,403
  • 5
  • 35
  • 65
0

You have different problems when trying to output 178908.90

First, the default implementation of c++ ostream normally outputs 178909, because as explained by Captain Giraffe, the default format does its best to avoid irrelevant digits and precision

You could try to force a fixed floating point with 2 digits in precision but then you will get 178908.91 (if you use float and not double). Because you would fall in second problem : in C++, floating point numbers (float or double) use IEEE-754 format which offers only about 7 decimal digits in precision, and internally it is more like : 178908.906

So the rule is : if you want to keep roughly the input precision, do not use numbers of more than 6 decimal digits for float and 14 for double, and if you want to keep strictly input precision, do not use floating point at all !

You can try to use decimal types as shown in that other answer, or build your own class.

Community
  • 1
  • 1
Serge Ballesta
  • 121,548
  • 10
  • 94
  • 199