为什么赢了';我的Java while循环停止并让我的程序终止吗?
我看到的结果是: 请输入一个整数,表示初始投资的全部美元价值:$为什么赢了';我的Java while循环停止并让我的程序终止吗?,java,loops,while-loop,Java,Loops,While Loop,我看到的结果是: 请输入一个整数,表示初始投资的全部美元价值:$ 10000 请输入投资利率的整数百分比,不包括百分号。 五, “10000”和“5”是我的输入。程序应该打印带有答案“15”的最终语句,但不执行任何操作,也不终止 import java.util.*; public class Investment { public static int years=0; public static void main(String[] args) {
10000
请输入投资利率的整数百分比,不包括百分号。
五, “10000”和“5”是我的输入。程序应该打印带有答案“15”的最终语句,但不执行任何操作,也不终止
import java.util.*;
public class Investment
{
public static int years=0;
public static void main(String[] args)
{
Scanner kbd = new Scanner(System.in);
System.out.println("Please enter an integer representing the whole dollar value of your initial investment: $");
int startBal=kbd.nextInt();
System.out.println("Please enter the whole number percentage, excluding the percent sign, of the interest rate on the investment.");
int interestRate=kbd.nextInt()/100;
int endBal=startBal*2;
int currentBal=startBal;
while (endBal>=currentBal)
{
currentBal=currentBal*interestRate+currentBal;
years++;
}
System.out.println("It will take "+years+" years to double your investment.");
}
}
因为interestRate
是一个int
,所以它被舍入为零
所以这一行:
int interestRate=kbd.nextInt()/100;
决心:
currentBal=currentBal*interestRate+currentBal;
所以这个值永远不会增加,也永远不会达到初始值的两倍,所以是无限循环
您必须将该行替换为:
=> currentBal=currentBal*0+currentBal;
=> currentBal=0+currentBal;
=> currentBal=currentBal;
您的利率被声明为int,因此它将被设置为0
您应该将所有值声明为双倍,因为我们谈论的是货币,我们希望精确:)您有一个
int
利率,当除以100
时,它变成0
。将其设置为double
,并使用double
literal100.0
进行除法,以强制进行浮点除法
double interestRate=kbd.nextInt()/100.0;
currentVal
变量也需要是一个double
我的输出和更改:
double interestRate=kbd.nextInt()/100.0;
这将使程序完成。但通常情况下。你做的整数除法是5/100,它=0的余数5。所以在你的计算中,你要乘以0,所以你的当前余额永远是0,永远不会达到最终余额。尝试使用双精度的利率,而不是整数
Please enter an integer representing the whole dollar value of your initial investment: $
10000
Please enter the whole number percentage, excluding the percent sign, of the interest rate on the investment.
5
It will take 15 years to double your investment.
当然它永远不会终止,你只是在增加年数,但同时变量是endBal和currentBal这是个好问题。代码在那里。输入、预期输出和实际输出都在那里。请不要在标题的“已解决”中进行编辑。在这里,通过单击答案旁边的复选标记,您可以“接受”解决问题的唯一答案。但是,当前BAL在迭代过程中不断被修改,不是吗?无限循环是因为用户除以5/100,它总是会是0,因此利息率和currentBal也是如此。@squidicate没问题:)接受答案,而不是将标题编辑为“已解决-…”,它将在问题页面上显示不同。
while (endBal>=currentBal)
{
currentBal=currentBal*interestRate+currentBal;
years++;
}