< previous page page_112 next page >

Page 112
These two statements employ some very advanced C++ notation. It's way too early in our look at C++ to explain fully the meaning of all the symbols and identifiers. But here's the general idea. setf is a void function associated with the cout stream. (Note that the dot, or period, between cout and setf is required.) The first function call ensures that floating point numbers are always printed in decimal form rather than scientific notation. The second function call specifies that the decimal point should always be printed, even for whole numbers. Our best advice is simply to use these statements just as you see them and not worry about the details.
The third issue-the number of decimal places to be displayed-is handled by the setprecision manipulator:
cout << setprecision(3) << x;
The parameter to setprecision specifies the desired number of decimal places. Unlike setw, which applies only to the very next item printed, the value sent to setprecision remains in effect for all subsequent output (until you change it with another call to setprecision). Here are some examples of using setprecision in conjunction with setw:
Value of xStatementOutput (box.gif means blank)
310.0cout << setw(10)
<< setprecision(2) << x;
box.gifbox.gifbox.gifbox.gif 310.00
310.0
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
cout << setw(10)
<< setprecision(5) << x;
box.gif 310.00000
310.0
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
cout << setw(7)
<< setprecision(5) << x;
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
310.00000 (expands to 9
columns)
4.827
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
cout << setw(6)
<< setprecision(2) << x;
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
box.gifbox.gif 4.83 (last displayed digit is
rounded off)
4.827cout << setw(6)
<< setprecision(1) << x;
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
box.gifbox.gifbox.gif 4.8 (last displayed digit is
rounded off)

Here, too, the total number of columns is expanded if the specified fieldwidth is too narrow. However, the number of columns for fractional digits is controlled entirely by the parameter to setprecision.
The following table summarizes the three manipulators we have discussed in this section:

 
< previous page page_112 next page >