patterncppMinor
Basic mortgage calculator
Viewed 0 times
calculatorbasicmortgage
Problem
I'm making a few forms of a mortgage calculator for my intro to computer science class. With inputs, I currently have it outputting the monthly payments. I'll eventually be outputting how long it will take to pay off the loan once I add some code. I'm just looking for suggestions for any easier/quicker ways to do it. It currently compiles and runs fine.
#include "math.h"
#include
using namespace std;
int main()
{
int a; //amount of the loan
double i; // the loan interest rate
int y; //years of the loan
int t = 12; //loan term in months
double mPayment; //variable for ouputting the payment
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
cout > a;
cout > i;
cout > y;
mPayment = (a * i) / (1 - pow(1+i,-t)); //Formula to figure mortgage payment amount
cout<< "\nYour Monthly Payment Amount is: $"<< mPayment; //prints out montyly payment amount
return 0;
}Solution
-
"math.h" should be `. The brackets are for system libraries whereas the quotes are for user-defined headers. The .h ending is mostly for C.
-
You don't actually need return 0 at the end of main(). It will do this same return for you at the very end.
-
You should consider input validation, at least if you decide to expand on this outside of the class. You could even allow the user the option to input via the command line, making this a bit more convenient.
-
You don't need those last two comments since they're already obvious. Only use them where explanation is needed for you and/or the reader.
-
Consider having the calculation done in a function for better maintainability:
// add this to better explain that value
const int loan_term = 12;
double calculateMortgagePayment(int loan, double interest_rate)
{
return (loan * interest_rate) / (1 - pow(1 + interest_rate, -loan_term));
}
int main()
{
// ...
// could also be const since value shouldn't change later
const double mortgagePayment = calculateMortgagePayment(loan, interest_rate);
// ...
}
I've taken into account@Conduit's advice regarding variable names. I've also kept the double` return type, which isn't really ideal for money. There are resources online that explain more about that.Code Snippets
// add this to better explain that value
const int loan_term = 12;
double calculateMortgagePayment(int loan, double interest_rate)
{
return (loan * interest_rate) / (1 - pow(1 + interest_rate, -loan_term));
}
int main()
{
// ...
// could also be const since value shouldn't change later
const double mortgagePayment = calculateMortgagePayment(loan, interest_rate);
// ...
}Context
StackExchange Code Review Q#120999, answer score: 8
Revisions (0)
No revisions yet.