为什么我的方法返回无穷大?

时间:2015-09-30 02:29:10

标签: java

十五.monthyPayment());每次运行它都会返回无穷大。我无法弄清楚为什么。我相信它与岁月有关,因为如果我将年份值改为等于某个数字,比如15,它就不会返回无穷大。我认为MyLoan十五应该为我改为15。

任何人都可以告诉我为什么这段代码会返回无穷大?

public class MyLoan {

    // instance members
    private double amountBorrowed;
    private double yearlyRate;
    private int years;
    public double A;
    public double n = years * 12;

    // public instance method
    public MyLoan(double amt, double rt, int yrs) {
        this.amountBorrowed = amt;
        this.yearlyRate = rt;
        this.years = yrs;
    }

    public double monthlyPayment() {

        double i = (yearlyRate / 100) / 12;

        A = (amountBorrowed) * ((i * (Math.pow(1+i,n))) / ((Math.pow(1 + i, n))-1));
        return A;
    }


    public static void main(String[] args) {

        double RATE15 = 5.75;
        double RATE30 = 6.25;
        double amount = 10000;
    }

    MyLoan fifteen = new MyLoan(amount, RATE15, 15);

    System.out.println(fifteen.monthlyPayment());

}

1 个答案:

答案 0 :(得分:3)

您需要在构造函数中初始化n

this.years = yrs;
this.n = yrs * 12;

否则,它使用years的默认值,即0

0除以Double.POSITIVE_INFINITY

相关问题