我正在从教科书中做练习题,但我无法弄清楚如何通过for
循环有效地做到这一点。
问:今年的大学学费是10000美元,每年增长5%。编写一个程序来显示从现在开始十年后 4 年学费的总成本。
这是我到目前为止想出的。
public class ComputeFutureTuition {
public static void main(String[] args) {
double baseTuition = 10000;
final double RATE = 1.05;
System.out.println("The total cost of 4 years tution");
for (int i = 0; i < 10; i++) {
// keep track of the next 4 year's tuition
double fourYearTuition = 0;
fourYearTuition = baseTuition + (baseTuition * RATE)
+ (baseTuition * RATE * RATE) + (baseTuition * RATE * RATE * RATE);
System.out.printf("%2d yrs from now: $%5.2f\n",
(i + 1), fourYearTuition);
// Increase the tuition by 5%
baseTuition = baseTuition * 1.05;
}
}
}
我如何通过只计算每年一次的学费来解决这个问题?现在我的解决方案是在每次迭代中抛出结果。(没有arrayList
或class
还没有,只是介绍了基础知识)。
期望输出:
The total cost of 4 years tution
1 yrs from now: $43101.25
2 yrs from now: $45256.31
3 yrs from now: $47519.13
4 yrs from now: $49895.08
5 yrs from now: $52389.84
6 yrs from now: $55009.33
7 yrs from now: $57759.80
8 yrs from now: $60647.79
9 yrs from now: $63680.18
10 yrs from now: $66864.19