1

所以我试图做的任务是找出一个本金达到某个值所需的年数。例如,我从 5000 美元开始,我想以 10% 的利率/年累积 15000 美元。我想知道该投资的持续时间有多长

这就是我到目前为止所做的

package com.company;

import java.util.Scanner;


public class InvestmentDuration {

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);

    System.out.println ("Initial Investment: ");
    double investment = input.nextDouble();

    System.out.println ("Rate as decimals: ");
    double rate = input.nextDouble();

    System.out.println ("Future Value: ");
    double FutureValue = input.nextDouble();

    double T = 0; //Initialise Duration//

    double EndValue = investment * Math.pow ((1+rate), T); //Formula of Simple Interest//

     while (EndValue < FutureValue) {
        T += 1.0;

         if (investment * Math.pow((1 + rate), T) == FutureValue);

        System.out.println("The Number of years it takes to accumulate $" + FutureValue + " is " + T + " years");
    }


}

输出:

The Number of years it takes to accumulate $15000.0 is 1.0 years
The Number of years it takes to accumulate $15000.0 is 2.0 years
The Number of years it takes to accumulate $15000.0 is 3.0 years
The Number of years it takes to accumulate $15000.0 is 4.0 years
The Number of years it takes to accumulate $15000.0 is 5.0 years
The Number of years it takes to accumulate $15000.0 is 6.0 years
The Number of years it takes to accumulate $15000.0 is 7.0 years
The Number of years it takes to accumulate $15000.0 is 8.0 years
The Number of years it takes to accumulate $15000.0 is 9.0 years
The Number of years it takes to accumulate $15000.0 is 10.0 years
The Number of years it takes to accumulate $15000.0 is 11.0 years
The Number of years it takes to accumulate $15000.0 is 12.0 years

如何只打印最后一行?

4

3 回答 3

3

最简单的解决方案是使用一些数学知识:

Math.log(goal/start) / Math.log(1+rate/100.0)

其中goalstart分别是结束时和开始时的金额,rate是利率,以百分比表示。

于 2017-03-08T10:50:43.077 回答
1

您需要使用循环(forwhile)。在这个循环中,您可以增加年份并计算新值。

请注意,我对变量做了一些更改:

  • 因为你想要一个整数循环,所以类型Tint
  • 我分别更改了EndValue和。Java 命名约定是camelCase,变量名的首字母较小。FinalValueendValuefinalValue
  • 我认为years是一个比 更好的名字T,但这是我个人的意见。如果你决定留下来T,至少它应该是一个小写字母t

然后你可以使用下面的代码。将 endValue 保存在变量中并不是真正必要的,因为它只使用一次。所以它可以被内联。但我决定接近你的问题。

    int years = 0;

    double endValue = investment;

    while (endValue < futureValue) {
        years++;
        endValue = investment * Math.pow((1 + rate), years);
    }

您应该知道,在此循环之后,年数endValue是大于或等于 futureValue 的完整年数。这意味着你不能有像 3.5 年这样的结果。如果你想计算,你应该使用亨利的解决方案。

于 2017-03-08T11:47:48.777 回答
0

这里有很多错误...首先,您的 IF 语句:它没有任何作用,因为您已用分号关闭它。此外,endvalue 不太可能等于 futurevalue,部分原因是浮点精度,部分原因是不太可能是整数年。所以我会尝试类似的东西:

double T = 0.0;
while(investment * Math.pow ((1+rate), T) < FutureValue) {
   T += 1.0;
}
System.out.println ("The Number of years it takes to accumulate the Future Value is: " +T+);

当然,或者您可以重新调整公式以直接计算 T。

于 2017-03-08T10:49:39.183 回答