试图找出我的抵押贷款计算器公式中的错误

问题描述 投票:0回答:1

我的任务是创建一个接受本金、利率和贷款期限的抵押贷款计算器。然后它会显示预期的每月付款和支付的利息总额。我也尝试使用静态方法来做到这一点。当我运行它时,每月付款和总利息显示

$NaN
。我不认为我的公式是错误的,因为当我用计算器计算时,我得到了正确的答案。

例如,本金为 53,000 美元,利率为 7.625%,期限为 15 年,应显示每月付款为 495.09 美元,支付的利息总额为 36,155.99 美元。

当前代码:

public class FinanceCalculator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        //Asking user which calculator they want to use
        System.out.println("Which calculator would you like to use? (1)Mortgage, (2)Future Value");
        byte userIn = scanner.nextByte();

        //Creating if statements for each calculator
        if(userIn == 1) {
            System.out.println("Enter the principle: ");
            float principle = scanner.nextFloat();
            System.out.println("Enter interest rate: ");
            float intRate = scanner.nextFloat();
            System.out.println("Enter loan length(In Years):" );
            int loanTerm = scanner.nextInt();
            float monthlyMortgage = (float) mortgageCalc(principle, intRate, loanTerm);
            float totaledInterest = ((loanTerm * 12 * monthlyMortgage) - principle);
            System.out.println("A $" + principle + " loan at " + intRate + "% interest for " + loanTerm + "years would have a $" + monthlyMortgage + "/mo payment with " +
                    "a total interest of $" + totaledInterest);
        }
    }

    //Creating mortgage calculator, Calculating monthly mortgage
    public static double mortgageCalc(float loan, float rate, int term) {
        float decimalIntRate = rate * 100;
        float mortgage = (float) ((((loan * (decimalIntRate / 12)) * Math.pow(1 + (decimalIntRate / 12), 12 * term)) / Math.pow(1 + (decimalIntRate / 12), 12 * term)) - 1);
        return mortgage;
    }
}

我希望它显示的结果是

A $53000.0 loan at 7.625% interest for 15years would have a $495.09/mo payment with a total interest of $36155.99

这是我遵循的公式

java methods
1个回答
0
投票

像这样尝试一下。

double I = .07625/12; // interest per month
double P = 53_000;    // principal
double T = 180;       // number of payments

double mort = P*I*Math.pow(1+I, T)/(Math.pow(1+I, T)-1);
System.out.printf("Mort = $%.2f%n",mort);
System.out.printf("Total Interest = $%.2f%n",mort*T-P);

打印

Mort = $495.09
Total Interest = $36115.99

© www.soinside.com 2019 - 2024. All rights reserved.