A Cplusplus program to calculate mortgage

Hey guys!
Im trying to write a program to calculate a mortgage and i got most of it but i am stuck on the actual problem solving. When i run through the practice problems the answer for monthly payment is off. Can anyone catch where i went wrong? my plan should look like this wen i run it:
Enter loan amount: 105000.00 // Given number
Enter annual interest rate: 0.115 // Given number
Enter number of years: 30 // Given number
The monthly payment is $ 1039.81 // output i'm supposed to receive. It is this number that keeps calculating wrong.


//
// Mortgage.cpp
// Apple Honey
// Jun. 22,2020
//
// CSCI-14 mortgage program
// Calculates mortgage payments using cpp
// A C++ program that calculates and displays monthly mortgage
//

#include<iostream>
#include<iomanip>
#include<cmath>

using namespace std;

// M - amount of the loan
// R - annual interest rate
// N - number if years

int main()
{
float loanAmount;
float AnnualInterest;
float m;
double r;
int n;
int t = 12; // 12 months
double monthlyPayment;

std::cout << "Enter loanAmount: ";
std::cin >> m;
std::cout << "\nEnter AnnualInterest rate: ";
std::cin >> r;
std::cout << "\nEnter number of years: ";
std::cin >> n;
monthlyPayment = (m * r) / (1 - pow(1 + r, -n));
std::cout << "\nyour payment is:$ " << monthlyPayment;

return 0;
}
Last edited on
Please use code tags when posting your code.

You should probably verify that your calculation is correct.

Great job.

Some notes here:

Setting the setprecision 2 for the loan amount and the interest rate to 3 could be make slight changes to your calculations.

My best practice is to subcode into different categories.

By separating the total formula into separate variables.

Such as
1
2
3
4
//Total loan with interest
float mr = (m*r);
etc..


This would make it easier to find your error.

For the reason why the calculation is off is because when calculating the mortgage rate, you would need to adjust the annual interest into monthly interest rates by using your t variable;
monthlyPayment = (m * r) / (1 - pow(1 + r, -n));
becomes
monthlyPayment = (m * r / t) / (1 - pow(1 + r / t, -t*n));

Adjust both r and n to account for t payments per year.

R = 0.115        # annual rate 
N = 30           # repayment duration in years
L0 = 105000      # initial loan
t = 12           # payments per year

P = ( R / t ) * L0 / ( 1 - ( 1 + R / t ) ** ( -t * N ) )
print( P )
Last edited on
Thank you so much soapbar and lastchance! and thank you for being so kind when helping me as well!
Topic archived. No new replies allowed.