Get wrong output while setting precision for ofstream

Hi, I have the following problem:
For the following code segment

vector <double> res;
res.push_back((double)number);
res.push_back((double)period);
res.push_back(...);

.....


cout.setf(ios_base::fmtflags(0), ios_base::floatfield);
cout.precision(10);
cout.setf(ios_base::left, ios_base::adjustfield);

for (unsigned int j=0;j<res.size();j++) {
cout << res[j] << "\t";
}

cout << "\n\n" ;

For some integers which were put in vector res I got a "wrong" answer, for example:
9 will be 8.999999488
43 will be 43.00000256
45 will be 44.99999744

If I take out the statement
cout.precision(10);
then all the integers will stay integers,that is 9 will be 9 etc.


This is actually embedded in a large program. If I just write another small program to repeat this phenomenon, it gives always the correct answer, that is 9 to 9, 43 to 43.

I am eager to know the reason. Thanks.

omaid


The problem is that conversion from int to float isn't 100% precise and can result in weird numbers like those.
hanst99 wrote:
The problem is that conversion from int to float isn't 100% precise

Actually, the problem is that floating-point numbers representation in computers is generally imprecise. Interesting read: http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems
Topic archived. No new replies allowed.