包含Math.pow()的公式产生意外结果

时间:2018-02-01 00:00:41

标签: java math double java.util.scanner equation

我正在尝试编写一个程序,该程序接受三个输入并通过以下等式表示:

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

我正在使用的正确示例结果表明,对于investment amount = 1000.56annual interest rate = 3.25(因此monthlyInterestRate = annual / 12)和numberOfYears = 1,我应该futureInvestmentValue = 1032.98

但是,我的程序声明了“$38045.96184617848”的最终结果(注意:我不需要回合)。

为什么会发生这种情况?

代码:

import java.util.Scanner;

public class num2_21 {

public static void main(String[] args) {

    System.out.println("This program was designed to calculate the future investment value of an investment. \n\n"
            + "When prompted, please enter the initial investment amount, interest APR (%), and length of investment (yrs). \n"
            + "Investment amount: ");
    Scanner in1 = new Scanner(System.in);
    double investAmount = in1.nextDouble();

    System.out.println("\n" + "Annual interest rate in percentage: ");
    Scanner in2 = new Scanner(System.in);
    double APR = in2.nextDouble();
    double monthlyInterest = APR / 12;

    System.out.println("\n" + "Length of investment: ");
    Scanner in3 = new Scanner(System.in);
    double investLength = in3.nextDouble();

    double futureInvestmentValue = investAmount * Math.pow((1 + monthlyInterest),(investLength*12));
    System.out.println("\n" + "Accumulated value: $" + futureInvestmentValue);


}

}

控制台:

This program was designed to calculate the future investment value of an investment. 

When prompted, please enter the initial investment amount, interest APR (%), and length of investment (yrs). 
Investment amount: 
1000.56

Annual interest rate in percentage: 
4.25

Length of investment: 
1

Accumulated value: $38045.96184617848

编辑:我忘记将APR除以100.我没有意识到我需要将其转换为小数。为疏忽道歉。我很欣赏额外的双眼。谢谢你的时间。

1 个答案:

答案 0 :(得分:1)

那么,这可能是因为425.0%的年利率不是太差,或者可能是因为你忘了除以100:

    double APR = in2.nextDouble() / 100.0;