好的,所以我正在研究的这个java程序应该计算30年的投资价值。它询问用户他们的起始投资在哪里以及百分比率(以小数形式)。我以为我已经弄明白但我的计划正在回归一些荒谬的价值观。有人可以看看我的代码并告诉我我做错了吗?
这些是提供给我的样本输出
投入的金额是多少? 1000
年利率是多少? 0.09
Years Future Value
----- ------------
1 $1093.81
2 $1196.41
...
29 $13467.25
30 $14730.58
我的输出是以数十亿和数万亿美元的价值返回......只是疯狂的东西。我提供的公式是
futureValue = investmentAmmount * (1 + monthlyInterestRate)^numberOfYears*12
这是我的程序的代码
import java.util.Scanner;
import java.text.NumberFormat;
import java.util.Locale;
import java.text.DecimalFormat;
public class InvestmentValue
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
NumberFormat df = DecimalFormat.getCurrencyInstance(Locale.US);
double investmentAmmnt;
// monthly interest rate
double mri;
int years;
System.out.print("What is the ammount invested? ");
investmentAmmnt = input.nextDouble();
System.out.print("What is the annual interest rate? ");
mri = input.nextDouble();
futureInvestmentValue(investmentAmmnt, mri, 30);
}
public static double futureInvestmentValue(double investmentAmmnt, double mri, int years)
{
NumberFormat df = DecimalFormat.getCurrencyInstance(Locale.US);
System.out.println("The amount invested: " + (df.format(investmentAmmnt)));
System.out.println("Annual interest rate: " + mri);
System.out.println("Years \t \t Future Value");
for (int i = 1; i <= years * 12; i++){
investmentAmmnt = investmentAmmnt * Math.pow(1 + (mri / 12),(years * 12));
if (i % 12 == 0){
System.out.println(i / 12 + "\t\t" + (df.format(investmentAmmnt)));
}
}
return investmentAmmnt;
}
}
答案 0 :(得分:2)
问题是公式futureValue = investmentAmmount * (1 + monthlyInterestRate)^numberOfYears*12
计算未来任何年度的投资价值。问题是你的循环计算超出了它的需要。那个公式只需要做一次。你的函数futureInvestmentValue不应该有for循环。
答案 1 :(得分:0)
以下是它的工作原理:
public static double futureInvestmentValue(final double investmentAmmnt, double mri, int years)
{
NumberFormat df = DecimalFormat.getCurrencyInstance(Locale.US);
double amount = investmentAmmnt;
System.out.println("The amount invested: " + (df.format(investmentAmmnt)));
System.out.println("Annual interest rate: " + mri);
System.out.println("Years \t \t Future Value");
for (int i = 1; i <= years ; i++){
amount = investmentAmmnt * Math.pow(1 + (mri /100),(i ));
System.out.println(i + "\t\t" + (df.format(amount)));
}
return amount;
}
您的代码存在很多问题......
- &GT;输出
Years Future Value
1 $1,030.00
2 $1,060.90
3 $1,092.73
4 $1,125.51
5 $1,159.27
6 $1,194.05
7 $1,229.87
8 $1,266.77
9 $1,304.77
10 $1,343.92
11 $1,384.23
12 $1,425.76
13 $1,468.53
14 $1,512.59
15 $1,557.97
16 $1,604.71
17 $1,652.85
18 $1,702.43
19 $1,753.51
20 $1,806.11
21 $1,860.29
22 $1,916.10
23 $1,973.59
24 $2,032.79
25 $2,093.78
26 $2,156.59
27 $2,221.29
28 $2,287.93
29 $2,356.57
30 $2,427.26