A program to calculate the amount of a periodic loan payment. The program prompts for the principal (the amount borrowed), the loan interest rate as an annual percentage rate (APR), and the loan duration in years. It assumes each period is one month, so it converts the APR to a periodic rate, the duration from years to periods, and calculates a monthly payment.
Test Cases
There are no simple or well-known test cases, so we must choose realistic values and calculate the payment with a calculator. We usually express the interest rate and loan duration in annual or yearly values. However, the formula uses the more general concept of "periods" or the number of payments per year, which could be annually (once per year), quarterly (four times per year), or monthly. For this example, we'll use monthly or twelve times per year. That means that we must convert the APR to a periodic interest rate of APR/12, and years to the number of periods: years*12.
P
R
N
payment
Case 1
100000
8% = 0.08
30
733.76
Case 2
100000
4% = 0.04
15
739.69
Formatting The Output
payment.cpp introduces two new formatting operations: setf and precision. Both operations are member functions of the cout (console output) object.
cout.setf(ios::fixed);
A set of flags controls cout's formatting. Each is like a light switch - they are either on or off. The setf (short for set flags) function turns the switches on or off. With the default cout settings, large numbers are displayed using scientific notation, which may not look right when printing monetary values. The ios::fixed flag or switch reconfigures cout so that it always displays numbers in a fixed-point format (no scientific notation) regardless of the number's size.
cout.precision(2);
The function configures cout to print two digits after the decimal point, which works well for U.S. currency. The output is rounded as necessary.
Note that these two statements only need to run once; cout remains as configured until the program ends or other statements reconfigure it.