Using setprecision
The setprecision manipulator has different effects depending on the compiler you are using. By default, the Microsoft Visual C++ compiler interprets the setprecision setting as the total number of digits on both sides of the decimal point. There is, however, a way to change this behavior.
Before using setprecision, set the fixed format option. Then the setprecision manipulator will set the number of digits to the right of the decimal point.
Consider the program from Exercise 6-6
#include <iostream.h>
#include <iomanip.h>
void main()
{
int i = 1499;
int j = 618;
int k = 2;
float a = 34.87432;
cout << setw(10) << i << setw(10) << j << setw(10) << k << endl;
cout << setw(10) << k << setw(10) << i << setw(10) << j << endl;
cout << setprecision(3) << setw(10) << a << endl;
}
As shown above, the final line of output created when compiled on the Microsoft Visual C++ compiler is 34.9 because the compiler assumes that you want to see three digits of precision overall.
The code below adds one line to the program. By setting the fixed format option before calling setprecision, the output shows three digits to the right of the decimal point.
#include <iostream.h>
#include <iomanip.h>
void main()
{
int i = 1499;
int j = 618;
int k = 2;
float a = 34.87432;
cout << setw(10) << i << setw(10) << j << setw(10) << k << endl;
cout << setw(10) << k << setw(10) << i << setw(10) << j << endl;
cout.setf(ios::fixed);
cout << setprecision(3) << setw(10) << a << endl;
}