Unexpected 'setprecision' behaviour.....

  • Thread starter mahesh.kanakaraj
  • Start date
M

mahesh.kanakaraj

Hi All,

I am new to C++ programming. I encounter an unexpected behavior of
'setprecision'.

The code snippet is :

#include <iostream.h>
#include <stdio.h>
#include <iomanip.h>

int main()
{
long double ld=1234567890.1234567898;

int prec = 0;

prec = cout.precision();
cout<<"Precision : "<<prec<<endl;

cout.flags(ios::fixed);
cout << setprecision(10) << ld << endl;

prec = cout.precision();
cout<<"Precision : "<<prec<<endl;

return 0;
}


The output I was expecting was :

Precision : 6
1234567890.1234567898
Precision : 10

But the output that was produced is :

Precision : 6
1234567890.1234567000
Precision : 10


What happened to the last 3 digits of the variable I am trying to
print.
Why is it filling zeros in the last three places? Is there any reasong
behind that?

Please enlighten me on this issue.

Thanks in Advance,
Mahesh K U
 
J

James Kanze

I am new to C++ programming. I encounter an unexpected behavior of
'setprecision'.
The code snippet is :
#include <iostream.h>
#include <stdio.h>
#include <iomanip.h>
int main()
{
long double ld=1234567890.1234567898;
int prec = 0;
prec = cout.precision();
cout<<"Precision : "<<prec<<endl;
cout.flags(ios::fixed);
cout << setprecision(10) << ld << endl;
prec = cout.precision();
cout<<"Precision : "<<prec<<endl;
return 0;
}
The output I was expecting was :
Precision : 6
1234567890.1234567898
Precision : 10
Why?

But the output that was produced is :
Precision : 6
1234567890.1234567000
Precision : 10
What happened to the last 3 digits of the variable I am trying to
print.

They were never there. The original number you specified is
doubtlessly not representable as a floating point number.
You're library implementation decided to output zeros rather
than random noise once it has output everything significant.
Why is it filling zeros in the last three places? Is there any reasong
behind that?

See http://docs.sun.com/source/806-3568/ncg_goldberg.html. It's
the reference for floating point; until you've understood it,
you shouldn't be using floating point.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,776
Messages
2,569,602
Members
45,185
Latest member
GluceaReviews

Latest Threads

Top