The next example continues the development of C++ formatted output initially introduced in Chapter 12. The first program demonstrates how to print a table of factorials using long doubles with the default right justification:
// // fact1.cpp // A C++ program that prints a table of // factorials for the numbers from 1 to 25. // Program uses the long double type. // Formatting includes precision, width and fixed // with default of right justification when printing. // Copyright (c) Chris H. Pappas and William H. Murray, 1998 //
#include <iostream.h> #include <iomanip.h>
main( ) { long double number,factorial;
number=1.0; factorial=1.0;
cout.precision(0); // no decimal place cout.setf(ios::fixed); // use fixed format
The next program/output pair demonstrates how to vary output column width and override the default right justification:
// // fact2.cpp // A C++ program that prints a table of // factorials for the numbers from 1 to 15. // Program uses the long double type. // Formatting includes precision, width, alignment, // and format of large numbers. // Copyright (c) Chris H. Pappas and William H. Murray, 1998 //
#include <iostream.h> #include <iomanip.h>
main( ) { long double number,factorial;
number=1.0; factorial=1.0;
cout.precision(0); // no decimal point cout.setf(ios::left); // left justify numbers cout.setf(ios::fixed); // use fixed format
The next example prints out a table of numbers, their squares, and their square roots. The program demonstrates how easy it is to align columns, pad with blanks, fill spaces with zeros, and control numeric precision in C++.
// // sqrt.cpp // A C++ program that prints a table of // numbers, squares, and square roots for the // numbers from 1 to 15. Program uses the type // double. Formatting aligns columns, pads blank // spaces with ‘0’ character, and controls // precision of answer. // Copyright (c) Chris H. Pappas and William H. Murray, 1998 //