我目前正在编写一个Java程序(用于学校),当用户输入帐户的起始余额时,该程序将打印两条语句。
例如,如果用户输入$10,000,将有两个同时打印的语句。一个告诉他们帐户需要多长时间才能达到10万美元,另一个则告诉他们达到100万美元。
现在我有了代码,我将在下面发布,它可以工作(它给我一个接近所需的结果),然而,我所面临的问题是数学本身。我会发布代码并解释:
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美元所需的时间是计算出来的,并打印该语句(第二次with循环相同,但有1,000,000美元)。因此,如果用户输入$10,000,第一个While循环的storedBalance变量应该是$20,000,$40,000,$80k,$160,但是按照我目前的计算,它是$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,所以括号内的逻辑保持不变,不随数字的变化而调整,但是存储的余额随循环的增加而增加。
所以我知道缺少了一些东西,因为第一年=$10,000,当它应该是$20,000,但是它需要的时间是正确的。我有一个感觉,我的数学是不正确的,因为我没有翻倍的初始值,我只是添加storedBalance到它。
任何和所有的答复都是非常感谢的。提前谢谢你。
发布于 2022-04-29 06:14:24
您应该在while循环之外初始化等于startBalance的startBalance。然后,在Then循环中,您只需在每次循环迭代( storedBalance )中使用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 + ".");}
https://stackoverflow.com/questions/72053463
复制相似问题