我正在制作一种方法,用于计算某一时期内某个金额的利率(这些值已在参数中定义)。 这是我到目前为止的代码:
public void balance(int amount, double rate, int year){
double yearlyRate = amount * rate;
double totalAmount;
System.out.print(amount + " :- " + " grows with the interest rate of " + rate);
for (int i = 0; i <= year; i++ ){
for ( int j = amount; j)
totalAmount = amount + yearlyRate;
System.out.println(i + " " + totalAmount);
}
}
我正在制作嵌套的for循环,因为你可以看到缺少代码的地方。在这里我遇到了一些麻烦。第一个for-loop贯穿多年,另一个用于计算总量。要清楚变量“int year”中定义的年份,假设它是7,那么该程序应该计算每年的增长量:
year1 totalAmount
year2 totalAmount
year3 totalAmount
and so on.....
主要方法如下:
public void exerciceG(Prog1 prog1) {
System.out.println("TEST OF: balance");
prog1.balance(1000, 0.04, 7);
}
我感谢任何帮助!
答案 0 :(得分:2)
这是一个要做的改变,但正如我在评论中提到的那样,可能还有很多其他事情要做:
totalAmount = totalAmount + amount + yearlyRate;
可写:
totalAmount += amount + yearlyRate;
您也可能希望删除for j
循环,因为它不会按原样执行任何操作。
<强> 修改 强>
这是猜测,因为我不确定我们知道目标是什么,但是如何:
public static void balance(int amount, double rate, int year){
double yearlyInterestPaid ;
double totalAmount = amount;
System.out.println(amount + " :- " + " grows with the interest rate of " + rate);
for (int i = 0; i <= year; i++ ){
yearlyInterestPaid = totalAmount * rate;
totalAmount += yearlyInterestPaid;
System.out.println(i + " " + totalAmount);
}
}
这是输出:
TEST OF: balance
1000 :- grows with the interest rate of 0.04
0 1040.0
1 1081.6
2 1124.8639999999998
3 1169.85856
4 1216.6529024
5 1265.319018496
6 1315.93177923584
7 1368.5690504052736
假设这是目标是合理的。
答案 1 :(得分:0)
我认为您正在寻找的答案是
for (int i = 0; i <= year; i++ ){
amount = amount + yearlyRate;
System.out.println(i + " " + amount);
}