1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
|
#include <iostream>
#include <iomanip>
#include <string>
#include <cmath>
#include <limits>
using namespace std;
int main() {
string again, x, y, z;
double monthly_payment, total_payment;
do
{
double x = valid_int("Loan Amount? "); //loan amount
double y = valid_int("Yearly Interest Rate? "); //amount of loan interest
int z = valid_int("Number of Years? "); //life of the loan (in months)
monthly_payment = calculate_mortgage(x,y,z);
total_payment = monthly_payment*z*12; ///****Trouble area******************
cout << "Monthly Payment: " << monthly_payment << endl;
cout << "Total Payment: " << total_payment << endl;
cout << "More calculations? (yes/no) " << endl;
cin >> again;
}
while (again== "yes");
return 0;
}
double calculate_mortgage(double loan_amount, double yearly_rate, int num_years) {
double monthly_payment = 0;
double monthlyRate = (yearly_rate / 100.00) / 12 ;
int numPayments = num_years * 12;
monthly_payment = monthlyRate * pow((1 + monthlyRate), numPayments) / (pow((1+monthlyRate), numPayments) -1) * loan_amount;
return monthly_payment;
}
int valid_int(string prompt) {
double input;
cout << prompt;
cin >> input;
// loop for a valid interger input
// static_cast check if number is an integer (ie. double is not valid
// cin.fail check if non numbers are entered
while (input != static_cast<int>(input) || cin.fail()) {
cin.clear(); //reset input error flag
//get rid of invalid chars,
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cout << "Invalid input. Please input an integer.\n" << endl;
cout << prompt; //reprompt input
cin >> input;
}
// get rid any invalid characters after the valid number input
// for example, if user entered, 102AB, the number will be 102 and
// discard anything after 102
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
return abs(input);
}
|