十五.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());
}
最佳答案
您需要在构造函数中初始化n
。
this.years = yrs;
this.n = yrs * 12;
否则,它将使用
years
的默认值,即0
。被
0
除以得到Double.POSITIVE_INFINITY
。关于java - 为什么我的方法返回无穷大?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32856783/