我的声明对我来说似乎没有意义,即使它有效 只要countYears 小于 timeLimit,我希望它只计算 的兴趣....所以如果我将timeLimit设置为5,它应该只计算5年值得关注,但我阅读当前的声明的方式,它似乎并没有这么说。也许我只是读错了?
public class RandomPractice {
public static void main(String[] args)
{
Scanner Keyboard = new Scanner(System.in);
double intRate, begBalance, balance;
int countYears, timeLimit;
System.out.println("Please enter your current investment balance.");
begBalance = Keyboard.nextDouble();
System.out.println("Please enter your YEARLY interest rate (in decimals).");
intRate = Keyboard.nextDouble();
System.out.println("Please enter how long (in years) you would like to let interest accrue.");
timeLimit = Keyboard.nextInt();
balance = begBalance * (1 + intRate);
countYears = 0;
/* The way I read this while statement is as follows
* "While countYears is GREATER than the timeLimit...calculate the balance"
* This makes no logical sense to me but I get the correct output?
* I want this code to calculate the investment interest ONLY as long as
* countYears is LESS than timeLimit **/
while (countYears >= timeLimit)
{
balance = balance + (balance * intRate);
countYears++;
}
System.out.println(balance);
}
}
答案 0 :(得分:1)
你所拥有的代码,不生成正确的数据,我的成绩单为8年,每年百分之一:
Please enter your current investment balance.
100
Please enter your YEARLY interest rate (in decimals).
.01
Please enter how long (in years) you would like to let interest accrue.
8
101.0
换句话说,只添加一年年,而不是八年。
所以要么你的编译器完全搞砸了,你的代码不是你想象的那样,或者你用来检查兴趣计算的测试数据和/或方法有点缺乏。
首先,正如您所预示的那样,您需要将条件更改为countYears < timeLimit
。
此外,您还需要在循环之前删除初始利息计算,因为这意味着您在存入资金后立即获得全年的利息。有了这两个变化:
balance = begBalance;
while (countYears < timeLimit) {
balance = balance + (balance * intRate);
countYears++;
}
然后你得到correct value:
Please enter your current investment balance.
100
Please enter your YEARLY interest rate (in decimals).
.01
Please enter how long (in years) you would like to let interest accrue.
8
108.28567056280801
答案 1 :(得分:0)
如果您将循环切换为<=
,那么您的循环根本就不会被执行。
现在你的输出是在循环之外计算的。