【发布时间】:2015-04-13 02:34:16
【问题描述】:
我目前正在尝试开发一个包含每月供款的复利计算器。我已经成功地能够使用以下代码行在没有每月供款的情况下进行复利计算,但无法弄清楚添加每月供款时的公式应该是什么。
double calculatedValue = (principalValue * Math.pow(1 + (interestRateValue/numberOfCompoundsValue), (termValue * numberOfCompoundsValue)));
当尝试通过贡献获得计算值时,我改变了这样做的方式。请参阅以下代码,我是如何处理这个问题的。
//The starting principal
double principalValue = 5000;
//Interest rate (%)
double interestRateValue = 0.05;
//How many times a year to add interest
int numberOfCompoundsValue = 4;
//The number of years used for the calculation
double termValue = 30;
//The monthly contribution amount
double monthlyContributionsValue = 400;
//How often interest is added. E.g. Every 3 months if adding interest 4 times in a year
int interestAddedEveryXMonths = 12/numberOfCompoundsValue;
//The total number of months for the calculation
int totalNumberOfMonths = (int)(12 * termValue);
for(int i = 1; i <= totalNumberOfMonths; i++)
{
principalValue += monthlyContributionsValue;
if(i % interestAddedEveryXMonths == 0)
{
principalValue += (principalValue * interestRateValue);
}
}
我认为这应该符合我的要求。每个月按供款金额增加本金,如果该月等于应添加利息的月份,则计算利息*利率并将其添加到本金中。
当使用上面的值时,我希望得到 $355,242.18 但得到 $10511941.97,这在我的银行帐户中看起来更好,但在我的计算中却没有。
如果有人能给我一些帮助或指出我哪里出错了,将不胜感激。
提前致谢
【问题讨论】:
-
尝试调试一下就知道问题出在哪里了
-
我已经对此进行了调试,一切看起来都像它应该做的那样,除了我不确定每次迭代应该计算的确切值之外。在盯着代码看太久之后,一定有一些非常明显的东西我错过了。