使用Math.pow方法

时间:2013-10-08 23:32:59

标签: java pow

我正在为我的入门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方法来翻译我教授方程式的指数部分。

3 个答案:

答案 0 :(得分: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;

答案 1 :(得分:2)

该公式可以翻译为Java:

double duration = numberOfYears * 12
double futureInvestmentValue = investmentAmount * Math.pow((1 + monthlyInterestRate), duration)

答案 2 :(得分:0)

这是Math.pow()

的使用方法

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

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