gpt4 book ai didi

java - 兴趣循环/编码初学者

转载 作者:行者123 更新时间:2023-12-01 22:12:44 25 4
gpt4 key购买 nike

我是一名非常初级的程序员,正在参加暑期类(class)。所以请简单地使用代码。我需要创建一个投资应用程序,计算 2,500 美元的投资如果以 7.5% 的年复利计算,需要多少年才能值(value)至少 5,000 美元。顺便说一句,我不知道 for 循环是什么。我只是不知道如何用循环来做到这一点,不是一个方程而是循环。请帮忙!!

这就是我到目前为止所拥有的。

public class Investment
{
// Main method
public static void main(String[] args)
{
int MaxAm=5000; //the final worth of investment
int Investment = 2500;
double Interest = 0.075;
double Time;
double TotalValue;

//BLAH

System.out.println("The amount of years it will take for a $2500 investment to be ");
System.out.println("worth at least $5000 if compounded annually at 7.5% is: "+Time);

}
}

最佳答案

为此,让我们了解一下什么是 while 循环。因为这个问题可以使用while循环来实现。

while(condition){
//things to do
}

这是 while 循环的基本架构。它检查条件。如果为 true,则执行括号内的所有指令。到达末尾后,它再次回到第一个括号并再次检查条件。如果条件成立,它将再次执行括号内的代码。只要条件不变为假,这种情况就会持续下去。如果为 false,java 会忽略下面括号内的指令并继续。

现在,就您的情况而言,您需要继续检查每年因利息产生的金额是否小于 TotalValue 。如果是这样,那么您将其模拟为一年。或者,在代码中,您可以将一年的计数加一。然后计算加利息后的金额并存储。如果它变得相等或更大,那么您需要停止添加年份的过程。当你已经达到你的答案时。确实非常简单。

amount<TotalValue当金额达到或超过 TotalValue 时变为 false .

  1. while(amount<TotalValue) {
  2. calculate amount after interest and store it.
  3. year++
  4. }

由于我们已经用起始金额初始化了 Investment,我们回收它并将金额的值存储在其中。不要被这个名字搞糊涂了。

public class Investment
{
// Main method
public static void main(String[] args)
{
int MaxAm=5000; //the final worth of investment
int Investment = 2500;
double Interest = 0.075;
double Time = 0;
double TotalValue = 5000;

while(Investment<TotalValue) {

Time++;
Investment = Investment + (Investment*Interest);

}

System.out.println("The amount of years it will take for a $2500 investment to be ");
System.out.println("worth at least $5000 if compounded annually at 7.5% is: "+Time);

}
}

关于java - 兴趣循环/编码初学者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31575329/

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