Reference: http://upliu.net/how-cout-out-2-precision.html
We all know that the printf () function in C can be very handy for keeping several decimal outputs
However, in C + + you can also control fractional retention, cout () and printf () or some differences
Cout<<setiosflags (ios::fixed) <<setprecision (2);//requires header file # include <iomanip>
Then output the real type variable that can retain 2 decimal places output, of course you want to keep three decimal places, Setprecision (3) on the line.
Setprecision refers to setting the output precision when there is no
Cout<<setiosflags (ios::fixed)
, the output format is a valid number of digits for the data, such as
2float a = 123.666;cout<<setprecision (5) <<a;
Will output 123.67 (note here that it will be rounded up). If the parameters in the setprecision are less than the integer digits, they will be output in exponential form, for example
2float a = 123.666;cout<<setprecision (2) <<a;
Will output 1.2e+002.
Setiosflags (ios::fixed) refers to a fixed floating-point display that retains n-bit output when setiosflags (ios::fixed) and Serprecision (n) two.
It is also important to note that each output is set only once, because the two scopes are subsequent objects, not just the latter.
How C + + cout preserves fractional output