Using Stream Manipulators to Format Numeric Output

The output statement in line 18 before the for loop and the output statement in line 27 in the for loop combine to print the values of the variables year and amount with the formatting specified by the parameterized stream manipulators setprecision and setw and the nonparameterized stream manipulator fixed. The stream manipulator setw(4) specifies that the next value output should appear in a field width of 4—i.e., cout prints the value with at least 4 character positions. If the value to be output is less than 4 character positions wide, the value is right justified in the field by default. If the value to be output is more than 4 character positions wide, the field width is extended rightward to accommodate the entire value. To indicate that values should be output left justified, simply output nonparameterized stream manipulator left (found in header <iostream>). Right justification can be restored by outputting nonparameterized stream manipulator right.

The other formatting in the output statements indicates that variable amount is printed as a fixed-point value with a decimal point (specified in line 18 with the stream manipulator fixed) right justified in a field of 21 character positions (specified in line 27 with setw(21)) and two digits of precision to the right of the decimal point (specified in line 18 with manipulator setprecision(2)). We applied the stream manipulators fixed and setprecision to the output stream (i.e., cout) before the for loop because these format settings remain in effect until they’re changed—such settings are called sticky settings and they do not need to be applied during each iteration of the loop. However, the field width specified with setw applies only to the next value output. We discuss C++’s powerful input/output formatting capabilities in Chapter 13, Stream Input/Output: A Deeper Look.

The calculation 1.0 + rate, which appears as an argument to the pow function, is contained in the body of the for statement. In fact, this calculation produces the same result during each iteration of the loop, so repeating it is wasteful—it should be performed once before the loop.


Image Performance Tip 5.1

Avoid placing expressions whose values do not change inside loops. Even if you do, many of today’s so-phisticated optimizing compilers will automatically place such expressions outside the loops in the generated machine code.



Image Performance Tip 5.2

Many compilers contain optimization features that improve the performance of the code you write, but it’s still better to write good code from the start.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.22.249.220