The behavior of the precision
function depends on the current settings of the floating point flags
and the kind of data that is output: Setting the precision has no effect on how integers are displayed bit it does
effect how floating point values (i.e., floats or doubles) are displayed. If both the fixed
and the
scientific
flags are off, then precision
sets the number of significant digits appearing
in the output; if either flag is on, then it sets the number of digits appearing after the decimal point. The code
in the following program is separated into four major blocks; the output is also grouped into corresponding blocks
to make it easier to see the impact of the formatting statements.
#define _USE_MATH_DEFINES #include <iostream> #include <cmath> using namespace std; int main() { cout << 123456789 << endl; cout << 123456789. << endl; cout << M_PI << endl; cout << endl; cout.precision(2); cout << 123456789 << endl; cout << 123456789. << endl; cout << M_PI << endl; cout << endl; cout.setf(ios::fixed); cout << 123456789 << endl; cout << 123456789. << endl; cout << M_PI << endl; cout << endl; cout.unsetf(ios::fixed); cout.setf(ios::scientific); cout << 123456789 << endl; cout << 123456789. << endl; cout << M_PI << endl; return 0; }
Output:
123456789 1.23457e+008 3.14159 123456789 1.2e+008 3.1 123456789 123456789.00 3.14 123456789 1.23e+008 3.14e+000
1.2
and 3.1
.