Section 2 - Building on the Past
7B.2.1 Mortgage, Resurrected
We left a thread hanging back when we did our mortgage calculator. All of the individual tasks were neatly tucked away in their own methods, but there was one irritating detail. The input() method was not capable of returning its input data through either functional returns or parameters (do you remember why neither of these modes was capable of transporting the three input values back to main()?). We had to resort to global variables (dblPrincipal, dblRate, dblYears) as a means of communicating the info among our various methods. And, as I said at the time, globals variables are not really meant to be used for this purpose.
Classes and reference parameters can be combined to give us a way around this dilemma. Before we present this solution, let's repeat the source and the screen shots of the mortgage calculator as we left it. Review it briefly to orient yourself for the discussion that follows:
#include <iostream> #include <string> #include <cmath> using namespace std; // method prototypes void stateInstructions(); void getInput(); double computeMonthlyPayment(); void reportResults(double result); // global variables shared by more than one method double dblPrincipal, dblRate, dblYears; int main() { double answer; stateInstructions(); getInput(); answer = computeMonthlyPayment(); reportResults(answer); } // gives an overview to user void stateInstructions() { string instructions; instructions = "\nThe following program will calculate the \n" "monthly payment required for a loan of D dollars \n" "over a period of Y years at an annual \n" "interest rate of R%.\n"; cout << instructions; } // gets input void getInput() { string prompt; // get principal prompt = "\nEnter amount of the loan. (only use numbers, \n" "please, no commas or characters like '$')\n" "Your loan amount: "; cout << prompt; cin >> dblPrincipal; // get interest prompt = "\nNow enter the interest rate (If the quoted rate is 6.5%, \n" "for example, enter 6.5 without the %.)\n" "Your annual interest rate: "; cout << prompt; cin >> dblRate; // get length of loan prompt = "\nEnter term of the loan in years: "; cout << prompt; cin >> dblYears; } // computes and returns answer double computeMonthlyPayment() { double dblTemp, dblPmt, dblMoRt, dblMonths; // convert years to months dblMonths = dblYears * 12; // convert rate to decimal and months dblMoRt = dblRate / (100 * 12); // use formula to get result dblTemp = pow(1 + dblMoRt, dblMonths); dblPmt = dblPrincipal * dblMoRt * dblTemp / ( dblTemp - 1 ); // now that we have computed the payment, return it return dblPmt; } // displays results and sign off void reportResults(double result) { string signoff; signoff = "\nThanks for using the Foothill Mortgage Calculator. \n" "We hope you'll come back and see us again, soon.\n\n"; cout.setf(ios::fixed); cout.precision(2); cout << "Your Monthly Payment: " << result << endl; cout << signoff; }
And here is a sample run:
