13.6.2. Floating-Point Precision (precision, setprecision)

We can control the precision of floating-point numbers (i.e., the number of digits to the right of the decimal point) by using either the setprecision stream manipulator or the precision member function of ios_base. A call to either of these sets the precision for all subsequent output operations until the next precision-setting call. A call to member function precision with no argument returns the current precision setting (this is what you need to use so that you can restore the original precision eventually after a sticky setting is no longer needed). The program of Fig. 13.9 uses both member function precision (line 22) and the setprecision manipulator (line 31) to print a table that shows the square root of 2, with precision varying from 0 to 9.


 1   // Fig. 13.9: fig13_09.cpp
 2   // Controlling precision of floating-point values.
 3   #include <iostream>
 4   #include <iomanip>      
 5   #include <cmath>
 6   using namespace std;
 7
 8   int main()
 9   {
10      double root2 = sqrt( 2.0 ); // calculate square root of 2
11      int places; // precision, vary from 0-9
12
13      cout << "Square root of 2 with precisions 0-9." << endl
14         << "Precision set by ios_base member function "
15         << "precision:" << endl;
16
17      cout << fixed; // use fixed-point notation
18
19      // display square root using ios_base function precision
20      for ( places = 0; places <= 9; ++places )
21      {
22         cout.precision( places );
23         cout << root2 << endl;
24      } // end for
25
26      cout << " Precision set by stream manipulator "
27         << "setprecision:" << endl;
28
29      // set precision for each digit, then display square root
30      for ( places = 0; places <= 9; ++places )
31         cout << setprecision( places ) << root2 << endl;
32   } // end main


Square root of 2 with precisions 0-9.
Precision set by ios_base member function precision:
1
1.4
1.41
1.414
1.4142
1.41421
1.414214
1.4142136
1.41421356
1.414213562

Precision set by stream manipulator setprecision:
1
1.4
1.41
1.414
1.4142
1.41421
1.414214
1.4142136
1.41421356
1.414213562


Fig. 13.9. Controlling precision of floating-point values.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.186.219