Section 6 - Mortgage Version 2
5A.6.1 Using the Functional Return in Mortgage Calculator
Let's modify the earlier program to use a functional return value. We change the large function:
#include <iostream> #include <string> #include <cmath> using namespace std; // method prototypes void stateInstructions(); double getInputAndComputeMonthlyPayment(); void sayGoodbye(); int main() { double answer; stateInstructions(); answer = getInputAndComputeMonthlyPayment(); cout << "Monthly Payment: " << answer << endl; sayGoodbye(); } // 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, computes and returns answer double getInputAndComputeMonthlyPayment() { string prompt; double dblPrincipal, dblRate, dblYears, dblMoRt, dblMonths; double dblTemp, dblPmt; // 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; // 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 ); return dblPmt; } // sign off void sayGoodbye() { 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 << signoff; }
Notice that main() now has its own local variable, answer which is charged with the responsibility of catching the return value from the getInputAndComputeMonthlyPayment() method. It is then used for the output.
We are also doing something that is going to be very important in all future assignments: separating the calculation operations from the I/O (Input/Output) operations. I am very much an advocate of not doing both I/O and calculations in the same method. When you see me do so, it is only because we have not (or had not) the tools to accomplish a clean separation. But once you know how to pass parameters and values between one method and another, I will expect you to never put too many different tasks in a single method, especially not calculation and I/O.
For the time being, we don't know how to pass two pieces of information to a method so we couldn't separate the input function from the number crunching function. But we will get there next time.