gpt4 book ai didi

java - 为什么我的 Java while 循环不停止并让我的程序终止?

转载 作者:行者123 更新时间:2023-11-30 06:17:00 25 4
gpt4 key购买 nike

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.");
}
}

我看到的输出是:

请输入代表您初始投资的全部美元值(value)的整数:$
10000
请输入投资利率的整数百分比,不包括百分号。
5

“10000”和“5”是我的输入。该程序应该打印我的最终陈述,答案是“15”,但它什么也没做,也没有终止。

最佳答案

int interestRate=kbd.nextInt()/100;

由于 interestRate 是一个 int,它会四舍五入为零。

所以这一行:

currentBal=currentBal*interestRate+currentBal;

决议:

=> currentBal=currentBal*0+currentBal;
=> currentBal=0+currentBal;
=> currentBal=currentBal;

所以这个值永远不会增加,所以永远不会达到初始值的两倍,所以无限循环。

您必须将此行替换为:

double interestRate=kbd.nextInt()/100.0;

关于java - 为什么我的 Java while 循环不停止并让我的程序终止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26410506/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com