【问题标题】:Using the Math.pow method使用 Math.pow 方法
【发布时间】:2013-10-08 23:32:59
【问题描述】:

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

【问题讨论】:

  • 请删除所有与Math.Pow 部分无关的代码以及所有不相关的介绍性文字。我们不想知道整个作业;我们想用不到 5 行的代码来看看确切的问题是什么。
  • 你是说你想知道调用Math.pow的语法吗?或者你是说你不知道要传递什么?你可能会从stackoverflow.com/questions/15457547/java-math-pow-method?rq=1得到一些见解
  • 是的,我想知道调用 Math.pow 的语法。大卫发布的链接似乎是我需要看到的,所以谢谢。下次我会尽量不要那么冗长。
  • 是的,在不删除所有不相关的东西的情况下,我们将开始指出您不需要 3 台扫描仪,只需一台,您调用 3 次,而不是您的 math.pow 问题是..,,

标签: java pow


【解决方案1】:

这个公式可以被翻译成Java:

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

【讨论】:

  • 这是一个非常具体的答案;非常感谢!
  • +1 以获得好的答案。非常小的一点 - 我会使用名称 numberOfMonths,而您使用的是 duration,只是为了让它更清晰一点。
【解决方案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;

【讨论】:

    【解决方案3】:

    这是Math.pow()的使用方法:

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

    其中 x = (1 + 月利率) 和 y = numberOfYears* 12

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-29
      • 1970-01-01
      • 2015-09-24
      • 2016-10-17
      • 2023-03-24
      • 2016-01-22
      • 2021-04-16
      相关资源
      最近更新 更多