0

我正在为我的入门 Java 编程课程做一个项目,我必须创建一个计算用户未来投资价值的程序。程序中必须提示用户三件事:他们的投资金额、年利率和投资年数。有了这些信息,程序应该能够计算用户的月利率以及他们未来的投资价值。

先从我教授的未来投资公式说起:

futureInvestmentValue = investmentAmount x (1 + monthlyInterestRate)^numberOfYears* 12

接下来,这是我到目前为止的代码:

public static void main(String[] args) {
    // Create scanner objects for investmentAmount, numberOfYears, and annualInterestRate
    Scanner investInput = new Scanner(System.in);
    Scanner rateInput = new Scanner(System.in);
    Scanner yearInput = new Scanner(System.in);

    // Declare variables
    int investmentAmount, numberOfYears;
    double annualInterestRate, rate, monthlyRate, futureInvestmentValue;

    // Create user inputs for investmentAmount, numberOfYears, and annualInterestRate
    System.out.print("Please enter your investment amount: ");
    investmentAmount = investInput.nextInt();

    System.out.print("Please enter your annual interest rate: ");
    annualInterestRate = rateInput.nextInt();

    System.out.print("Please enter the number of years for your investment: ");
    numberOfYears = yearInput.nextInt();

    // Variable assignments
    rate = annualInterestRate / 100;
    monthlyRate = rate / 12;
    futureInvestmentValue = investmentAmount * (1.0 + monthlyRate);

    //Output
    System.out.print("Your annual interest rate is " + rate +
        " and your monthly interest rate is " + monthlyRate);

    investInput.close();
    rateInput.close();
    yearInput.close();
}

我根据用户的输入计算了用户的月利率,并开始将我教授的公式翻译成 Java 语言。
但是,我不知道如何使用 Math.pow 方法来转换教授方程的指数部分。

4

3 回答 3

2
// if you want e^b:
double result = Math.exp(b);

// if you want a^b:
double result = Math.pow(a, b);

不要忘记:

import java.lang.Math;
于 2013-10-08T23:38:17.037 回答
2

该公式可以翻译成 Java 为:

double duration = numberOfYears * 12
double futureInvestmentValue = investmentAmount * Math.pow((1 + monthlyInterestRate), duration)
于 2013-10-08T23:39:04.850 回答
0

这是如何使用Math.pow()

Math.pow ( x,y ); // x^y

其中 x = (1 +monthlyInterestRate) 和 y = numberOfYears* 12

于 2013-10-08T23:39:51.733 回答