while循环计算问题

While loop calculation issue

我目前正在开发一个 Java 程序(用于学校),该程序在用户输入其帐户的起始余额时打印两份报表。

因此,例如,如果用户输入 $10,000,则会同时打印两个语句。一个告诉他们他们的帐户需要多长时间才能达到 100,000 美元,另一个告诉他们何时达到 1,000,000 美元。

现在我有了代码,我将在下面 post,它可以工作(它得到的结果接近所需的结果),但是,我遇到的问题是数学本身。我会 post 代码并解释:

public static void main(String[] args) {
    int startBalance = 0;
    int storedBalance = 0;
    int years = 0;
    try (Scanner stdln = new Scanner(System.in)) {
        System.out.println("Please enter your starting balance: ");
        startBalance = stdln.nextInt();
    }
    
    while (storedBalance < 100000)
    {   
        storedBalance = startBalance + (storedBalance * 2) ;
        ++years;
    } 
    System.out.println("It will take " + years + " year(s) for your bank balance to reach " + storedBalance + ".");
    
    while (storedBalance < 1000000)
    {   
        storedBalance = startBalance + (storedBalance * 2);
        ++years;
    } 
    System.out.println("It will take " + years + " year(s) for your bank balance to reach " + storedBalance + ".");
}

}

所以理论上,startBalance 应该翻倍,直到达到 100,000 美元或更多,在这种情况下,计算达到超过 100,000 美元所需的年数并打印语句(与第二个 While 循环相同,但为 1,000,000 美元).因此,如果用户输入 10,000 美元,第一个 While 循环的 storedBalance 变量应该为 20,000 美元、40,000 美元、80,000 美元、160,000 美元,但根据我目前的数学计算,它为 10,000 美元、30,000 美元、70,000 美元、150,000 美元。

我也试过:

storedBalance = (startBalance * 2) + storedBalance;

它有效,但问题是它没有将数量加倍(10k 到 20k,20k 到 40k,40k 到 80k,等等)它只是在之前的数字上增加 20k,这是有道理的,因为逻辑在该语句中,如果 startBalance 为 10k,则为:(10,000 * 2) + storedBalance,因此括号内的逻辑保持不变,不会随着数字的变化而调整,但存储的余额会随着每个循环而增加。

所以我知道缺少某些东西,因为第 1 年 = 1 万美元,而它应该是 2 万美元,但到达那里所需的年数是正确的。我感觉我的数学不正确,因为我没有将初始值加倍,我只是将 storedBalance 添加到它。

非常感谢任何和所有回复。提前谢谢你。

您应该在 while 循环外将 storedBalance 初始化为 startBalance。然后在 while-loops 中,您只需将 storedBalance 值每 loop-iteration(年)加倍 storedBalance = storedBalance * 2;

public static void main(String[] args) {
int startBalance = 0;
int years = 0;
try (Scanner stdln = new Scanner(System.in)) {
    System.out.println("Please enter your starting balance: ");
    startBalance = stdln.nextInt();
}
int storedBalance = startBalance;
while (storedBalance < 100000)
{   
    storedBalance *= 2;
    ++years;
} 
System.out.println("It will take " + years + " year(s) for your bank balance to reach " + storedBalance + ".");

storedBalance = startBalance;
years = 0;
while (storedBalance < 1000000)
{   
    storedBalance *= 2;
    ++years;
} 
System.out.println("It will take " + years + " year(s) for your bank balance to reach " + storedBalance + ".");

}