无法弄清楚为什么循环没有得到正确的总和

问题描述

我正在尝试制作抵押计算器,无论出于何种原因,它的本金和利息总和都不正确。是否有可能因为它被添加到do-while循环内而弄错了吗?当我运行程序时,本金为8233.68,利息为11423.59。如果用计算器对其进行汇总,则本金应为8209.30,利息应为11447.97。

double termSelection = 0.0359;
double principal = 325000;
double effectiveMonthlyRate = 0.0029695338579054376;  
double monthlyPayment = 1638.1053796234314;
double monthlyInterest = (principal * effectiveMonthlyRate);
double monthlyPrincipal = (monthlyPayment - monthlyInterest);
double closingBalance = (principal - monthlyPrincipal);
 
int month = 1;
double totalPrincipal = 0;
double totalInterest = 0;
termSelection *= 100;

//monthly payment schedule header
System.out.println("");
System.out.printf("%nInterest Rate: %.2f%%",termSelection);
System.out.printf("%n%53s","Monthly Payment Schedule");
termSelection /= 100;

//monhtly payment schedule body
System.out.printf("%n%5s%14s%15s%15s%15s%15s","Month","Open Bal","Payment","Princ","Interest","Closing Bal");

do{
    System.out.printf("%n%5s%14.2f%15.2f%15.2f%15.2f%15.2f",month,principal,monthlyPayment,monthlyPrincipal,monthlyInterest,closingBalance);
    
    month++;
    
    principal = closingBalance;
    
    monthlyInterest = principal * effectiveMonthlyRate; 
    
    monthlyPrincipal = monthlyPayment - monthlyInterest;
    
    closingBalance = principal - monthlyPrincipal;
    
    totalPrincipal = totalPrincipal + monthlyPrincipal;
    
    totalInterest = totalInterest + monthlyInterest;
    }
while (month <= 12); 

System.out.println("");
for (int count = 0; count <= 80; count++){
    System.out.print('=');
}

System.out.printf("%n%5s%44.2f%15.2f","Ttls",totalPrincipal,totalInterest);

解决方法

问题在于您甚至在进入循环之前就已经在进行计算

double closingBalance = (principal - monthlyPrincipal);

应该是

double closingBalance = (principal);

输出

 Ttls                                     8209.30       11447.97
,

您将在循环的第一次迭代中重新计算monthlyInterest和monthlyPrincipal的初始值,然后将它们添加到总计中。首先将它们添加到总计中,然后重新计算。

var d = new Date();
console.log("Date = " + d); //  Fri Apr 16 2021 20:00:00 GMT-0400 (Eastern Daylight Time)
var n = d.getFullYear();
console.log("Current Year = " + n); //2021