Introduction: Everyone in the program to write more or less encounter this problem, especially for some beginners will appear this problem, do an ACM contest of students will certainly use C language printf format control output, but accustomed to use C + + students are not a little way not ah, this blog will introduce C + + is somewhat complex, but it is also a way to use it.
Let's take a look at the code first (for example, with the four integers and the average):
For four integers #include <iostream> #include <iomanip> using namespace Std;int main () {int a,b,c,d,e;double f; cin>>a>>b>>c>>d;e=a+b+c+d;//e store and, for the integer f= (double) e/4;//f store the average, for double printf ("%d%.1f\n", E, f);//c language control format output, leaving a decimal place after the decimal point//c++ output stream format control output cout<<e<< "" <<setiosflags (ios::fixed) << Setiosflags (Ios::right) <<setprecision (1) <<f;return 0;}
You can see that the C language printf is very easy to control the format, "%m.nf": Output floating-point number, M is width, n is the right digit of the decimal point
Also note that the cout output stream for C + + uses two functions setiosflags () and Setprecision ()
Here are the two functions:
Setiosflags () function: Setiosflags is a C + + operator contained in a namespace iomanip that performs actions within a specified area of a parameter;
Iso::fixed is one of the parameters of the operator Setiosflags, indicating the output of real numbers in fixed-point mode;
Iso::right is also a setiosflags parameter that specifies the right-aligned output within the specified area.
Setprecision () function: Setprecision (n) controls the output stream to display the number of floating-point numbers as N. C + + default stream output numeric value bit is 6
Cout<<setiosflags (ios::fixed) <<setiosflags (ios::right) <<setprecision (1);
Together, it means: output a right-aligned 1-bit floating-point number, that is, the function is to control the right side of the decimal digits.
Resources:
Setprecision () and Setiosflags () (c + + decimal to n-bit)
Printf () Output format Control setprecision () and Setiosflags () (c + + decimal point to n-bit)
Two methods that are accurate to n digits after the decimal point