Next: Summary
Up: Further Assignment Statements &
Previous: Formatting of output
The following example program tabulates values of the sin function, using
manipulators to align the output neatly in columns. The for
statement, which will be covered in Lesson 18,
repeats the statements after it. In this case, i
takes values
0, 1, 2, ... 16.
// IEA Oct 1995 // Outputs a table of x and sin(x) // Uses manipulators for output #include <iostream.h> #include <math.h> #include <iomanip.h> void main() { float x; int i; cout << setiosflags(ios::fixed | ios::showpoint); for (i = 0; i <= 16; i++ ) { x = 0.1 * i; cout << setprecision(1) << setw(4) << x; cout << setprecision(6) << setw(10) << sin(x) << endl; } }
Download program.produces nicely aligned tabular output as follows:
0.0 0.000000 0.1 0.099833 0.2 0.198669 0.3 0.295520 . . . 1.5 0.997495 1.6 0.999574
Note how the iosflags
were set at the beginning but that the
precision and width were set individually in the cout
stream output as
required.