first off this is a class assignment so i would appreciate help but just hints as i want to learn. I have to calculate monthly payment based off of interest rate etc as seen in my code but something is off with my calculation. My output reads nan which i believe is not a number. I have been trying to figure out where i am going wrong to no avail,any suggestions on how to correct this issue? Thanks in advance.
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
//collect payment info
double loanAmount = 0;
double anualRate = 0;
double monthlyIntRate = 0;
int numOfPayment = 0;
double monthlyPayment = 0;
double amountPaidBack = 0;
double interestPaid = 0;
cout << "Enter loan amount: ";
cin >> loanAmount;
cout << "Enter Anual Interest Rate: ";
cin >> anualRate;
cout << "Enter Payments made: ";
cin >> numOfPayment;
//calculate montly payment
monthlyPayment = (loanAmount * pow(monthlyIntRate + 1, numOfPayment) * monthlyIntRate) / ( pow(monthlyIntRate + 1, numOfPayment) - 1);
//calculate amount paid back
amountPaidBack = monthlyPayment * numOfPayment;
//calculate interest paid
monthlyIntRate = anualRate / 12;
interestPaid = monthlyIntRate * numOfPayment;
//split input from calculated output
cout << "-----------------------------\n" << endl;
//Display the calulated data
cout << fixed;
cout << setprecision(2);
cout << "Loan Amount: " << setw(15) << "$ "<< right << loanAmount << endl;
cout << "Monthly Interest Rate: " << setw(14) << monthlyIntRate << "%" << endl;
cout << "Number of Payments: " << setw(17) << numOfPayment << endl;
cout << "Montly Payment: " << setw(19) << "$ " << monthlyPayment << endl;
cout << "Amount Paid Back: " << setw(17) << "$ " << amountPaidBack << endl;
cout << "Interest Paid: " << setw(18) << "$ " << interestPaid << endl;
return 0;
Output:
Loan Amount: $ 100000.00
Monthly Interest Rate: 1.00%
Number of Payments: 36
Montly Payment: $ nan
Amount Paid Back: $ nan
Interest Paid: $ 36.00
You’re dividing by zero. it occurs in this line:
The value stored in
monthlyIntRateis zero, sopow(monthlyIntRate + 1, numOfPayment)eqauls to(0 + 1) ^ numOfPayment, which is 1. So,pow(monthlyIntRate + 1, numOfPayment) - 1)is 0.