My code is supposed to calculate the yearly balance using compounding monthly interest with contributions, but it returns values that are the incorrect amount. As an example, initialInvestment is 1869.57, monthlyDeposit is 14, interestRate is 9.50, and numberOfYears is 19. It’s supposed to return 20193.81, but instead it returns 20264.33. How would I fix it so it returns the correct values?
double balanceWithMonthlyDeposit(double initialInvestment, double monthlyDeposit, double interestRate, int numberOfYears){
double interestEarned;
double previousBalance = initialInvestment; // Principal
double interest = (interestRate / 100.0) / 12.0; // Convert interest rate to decimal
for (int i = 0; i < numberOfYears; ++i) { // For each year
double yearlyInterest = 0;
for (int j = 0; j < 12; ++j) { // For each month
interestEarned = previousBalance + monthlyDeposit;
interestEarned = interestEarned * interest;
yearlyInterest = yearlyInterest + interestEarned;
previousBalance = previousBalance + monthlyDeposit + interestEarned;
}
printDetails(i + 1, previousBalance, interestEarned);
}
return previousBalance;
// return the ending balance
}
I’ve tried implementing a formula that I found online but it didn’t work as intended.
kg333 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.