我的任务是创建一个按照描述运行的程序,用 Java 编程:
说明储蓄账户中货币的增长。用户输入初始金额(十进制)和利率,用于计算货币加倍之前的年数和货币达到一百万美元之前的年数。 (您将需要使用多于1个循环)。
注意:每年年底的余额为
(1 + r)*余额
其中余额是先前的余额,r是十进制形式的年利率。
但是,我在代码中找不到错误。会发生什么事情,它会不断写入"你的余额将会翻倍。然后数字无限增长。
以下是代码:
扫描仪输入=新扫描仪(System.in); 双年= 0; double futureVaule;
System.out.print("Please enter the amount of money you would like to deposit, as a decimal:\n>>");
double balance = input.nextDouble();
System.out.print("Please enter the interest rate of your deposit, as a percent:\n>>");
double r = input.nextDouble();
do
{
futureValue = (1 + r) * balance;
years = years + 1;
System.out.println("Your balance will double in "
+ Math.round(years) + " year(s).");
}while(futureValue <= balance*2);
答案 0 :(得分:1)
这应该有效
futureValue = balance;
double doubleBalance = balance*2;
while(futureValue <= doubleBalance)
{
futureValue += futureValue * (( 1 + r)/100);
years++;
}
System.out.println("Your balance will double in "
+ years + " year(s).");