好的,所以我是Java新手。我有一个程序,在询问用户节省金额和年利率后计算复合值。我很难将它变成for循环,但我觉得我有点接近?我脑子里最难的部分是了解如何将最后几个月的总数用于新计算。
这是我目前的复合值公式:
firstMonth = savingAmount * (1 + monthlyInterestRate);
secondMonth = (savingAmount + firstMonth) * (1 + monthlyInterestRate);
thirdMonth = (savingAmount + secondMonth) * (1 + monthlyInterestRate);
fourthMonth = (savingAmount + thirdMonth) * (1 + monthlyInterestRate);
fifthMonth = (savingAmount + fourthMonth) * (1 + monthlyInterestRate);
sixthMonth = (savingAmount + fifthMonth) * (1 + monthlyInterestRate);
显然很难看,应该是for循环。 saveAmount再次是用户输入,annualInterestRate是用户输入。 monthlyInterestRate是annualInterestRate / 12.
这是我到目前为止的for循环。
for (int i = 1; i <= 6; i++ );
{
sixthMonth = savingAmount * Math.pow(1+monthlyInterestRate, 6);
}
我还在学习for循环,但是我的代码并没有说它加起来小于或等于6?虽然这些都符合我提供的公式。不,你不必回答这个问题,但如果你能引导我朝着正确的方向发展,那就太好了。那么我将如何开始转换呢?如果需要,请随时询问更多信息。
答案 0 :(得分:2)
试试这个:
for (int i = 1; i <= 6; i++) {
monthAmount = (savingAmount + monthAmount) * (1 + monthlyInterestRate);
}
这可以让你得到同样的答案。
您在正确的轨道上,但这将允许您使用公式中的前几个月金额。无论您希望循环运行多长时间,此代码也将起作用。
答案 1 :(得分:2)
我实际上建议使用复利公式 A = P (1 + r/n) ^ nt
。
所以你可以将所有这些减少到:
compoundValue = savingAmount * Math.pow(1 + monthlyInterestRate/12,
monthlyInterestRate * yearsCompounded);
答案 2 :(得分:1)
如果您想了解每个月会有多少节省,我建议将这些金额存储在列表中以便于查找。
public static void main(String args[]) {
double savingsAmount = 543.23;
double annualInterestRate = 0.85; // %
double monthlyInterestRate = annualInterestRate / 12;
List<Double> savings = new ArrayList<Double>();
savings.add(savingsAmount); // month 0
int monthsInTheFuture = 6;
double compoundInterest = 1 + monthlyInterestRate;
for (int i = 1; i <= monthsInTheFuture; i++) {
double previousSavings = savings.get(i-1);
double nextSavings = previousSavings * compoundInterest;
savings.add(nextSavings);
}
System.out.println(savings);
}