Consider the following problem statement:
A person invests $1000.00 in a savings account yielding 5 percent interest. Assuming that all interest is left on deposit in the account, calculate and print the amount of money in the account at the end of each year for 10 years. Use the following formula for determining these amounts:
a = p ( 1 + r )n
where
p is the original amount invested (i.e., the principal),
r is the annual interest rate,
n is the number of years and
a is the amount on deposit at the end of the nth year.
The for
statement (Fig. 5.6, lines 21–28) performs the indicated calculation for each of the 10 years the money remains on deposit, varying a control variable from 1 to 10 in increments of 1. C++ does not include an exponentiation operator, so we use the standard library function pow (line 24). The function pow(x, y)
calculates the value of x
raised to the y
th power. In this example, the algebraic expression (1 + r)n is written as pow(1.0 + rate, year)
, where variable rate
represents r and variable year
represents n. Function pow
takes two arguments of type double
and returns a double
value.
1 // Fig. 5.6: fig05_06.cpp
2 // Compound interest calculations with for.
3 #include <iostream>
4 #include <iomanip>
5 #include <cmath> // standard math library
6 using namespace std;
7
8 int main()
9 {
10 double amount; // amount on deposit at end of each year
11 double principal = 1000.0; // initial amount before interest
12 double rate = .05; // annual interest rate
13
14 // display headers
15 cout << "Year" << setw( 21 ) << "Amount on deposit" << endl;
16
17 // set floating-point number format
18 cout << fixed << setprecision( 2 );
19
20 // calculate amount on deposit for each of ten years
21 for ( unsigned int year = 1; year <= 10; ++year )
22 {
23 // calculate new amount for specified year
24 amount = principal * pow( 1.0 + rate, year );
25
26 // display the year and the amount
27 cout << setw( 4 ) << year << setw( 21 ) << amount << endl;
28 } // end for
29 } // end main
This program will not compile without including header <cmath>
(line 5). Function pow
requires two double
arguments. Variable year
is an integer. Header <cmath>
includes information that tells the compiler to convert the value of year
to a temporary double
representation before calling the function. This information is contained in pow
’s function prototype. Chapter 6 summarizes other math library functions.
Common Programming Error 5.4
Forgetting to include the appropriate header when using standard library functions (e.g., <cmath> in a program that uses math library functions) is a compilation error.
18.118.37.254