Formatting console output
The following functions are flow operation, i.e. in between "<<" or ">>" (flow operator), the definition of <iomanip> header file in
#include <iomanip>
operating | description |
setprecision(n) | A float setting accuracy |
fixed | Decimal display, often used in combination with setprecision (n) |
showpiont | Even if no decimal places should be padded with zeros, is often used in combination with setprecision (n) |
setw(width) | Designated printing width of the field |
left | Adjust the output to the left |
right | Adjust the output to the right |
1. setprecision(n)
double number = 123.4567;
cout << setprecision(3) << number << endl;
//123
cout << setprecision(4) << number << endl;
//123.5
cout << setprecision(5) << number << endl;
//123.46
cout << setprecision(6) << number << endl;
//123.457
2.fixed
Number = 123,232,456,743.4567 Double ;
COUT Number << << endl;
//1.23232e+011
// This is a form of scientific notation, i.e., 1.23232 * 10 ^ 11
// To display in the form of a non-scientific notation is necessary to use fixed function
COUT fixed << << number << endl;
//123232456743.456696
// accuracy problems due to the floating-point decimal place cause some deviation
COUT << << fixed setPrecision (. 4) number << << endl; //123232456743.4567
3. showpoint
cout << setprecision(6); cout << 12.3 << endl; //12.3 cout << showpoint << 12.3 << endl; //12.3000 cout << showpoint << 12.30 << endl; //12.3000
4. setw(width)
cout << setw(8) << "C++" << setw(6) << 101 <<endl; cout << setw(8) << "Java" << setw(6) << 101 <<endl; cout << setw(8) << "HTML" << setw(6) << 101 <<endl;
Result of the program:
Note: The following functions can only affect a stew that is, if there is no setw (6), 101 will be close to the front.
This time they have a problem is that when we set the width smaller than the width of the output terms of what will happen?
A: When we set the width is less than the width of the output items, the width will automatically increase the width of the output terms, equivalent no width.
5. left和right
setw operation default setting is right-aligned, so that we can use the left left-aligned
cout << left; cout << setw(8) << "C++" << setw(6) << 101 <<endl; cout << setw(8) << "Java" << setw(6) << 101 <<endl; cout << setw(8) << "HTML" << setw(6) << 101 <<endl;