Java我的贷款类公式返回无穷大
除了每月贷款计算器的返回值外,我的代码运行得非常好。无论是我的月付款还是总付款,它都会不断返回无穷远。请帮我拿配方。这是一个家庭作业。我需要知道的是,我是否执行了错误的公式。我感觉它试图除以0,然后返回无穷大,但我可能错了Java我的贷款类公式返回无穷大,java,Java,除了每月贷款计算器的返回值外,我的代码运行得非常好。无论是我的月付款还是总付款,它都会不断返回无穷远。请帮我拿配方。这是一个家庭作业。我需要知道的是,我是否执行了错误的公式。我感觉它试图除以0,然后返回无穷大,但我可能错了 public class MyLoan { private double amountBorrowed; private double yearlyRate; private int years; public double A; public double n = ye
public class MyLoan
{
private double amountBorrowed;
private double yearlyRate;
private int years;
public double A;
public double n = years * 12;
public MyLoan(double amt, double rt, int yrs)
{
amountBorrowed = amt;
yearlyRate = rt;
years = yrs;
}
public double getAmountBorrowed()
{
return amountBorrowed;
}
public double getYearlyRate()
{
return yearlyRate;
}
public int getYears()
{
return years;
}
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 double totalPayment()
{
return A * (years * 12);
}
public String toString()
{
return "Loan: " + "$" + amountBorrowed + " at " + yearlyRate + " for " + years + " years";
}
public static void main(String[] args)
{
final double RATE15 = 5.75;
final double RATE30 = 6.25;
StdOut.println("***** Welcome to the Loan analyzer! *****");
String ans = "Y";
do {
StdOut.print("\n Enter the principle amount to borrow: ");
double amount = StdIn.readDouble();
MyLoan fifteenYears = new MyLoan(amount, RATE15, 15);
MyLoan thirtyYears = new MyLoan(amount, RATE30, 30);
double amount15 = fifteenYears.monthlyPayment();
double total15 = fifteenYears.totalPayment();
double amount30 = thirtyYears.monthlyPayment();
double total30 = thirtyYears.totalPayment();
StdOut.println("===========ANALYSES==========");
StdOut.println(fifteenYears);
StdOut.println("Monthly payment = " + "$" + amount15);
StdOut.println("Total payment = " + "$" + total15);
StdOut.println("");
StdOut.println("");
StdOut.println(thirtyYears);
StdOut.println("Monthly payment = " + "$" + amount30);
StdOut.println("Total payment = " + "$" + total30);
StdOut.println("=============================");
StdOut.print("\n ** Do you want to continue (y/n)? ");
ans = StdIn.readString();
} while (ans.toUpperCase().equals("Y"));
StdOut.println("\n********** Thank you. Come again! **********");
}
}
计算利息的方法有很多,最常见的是
A = amountBorrowed * (yearlyRate / 100) / 12;
你应该自己调试这个,但我会给你一个提示。什么是1^n(其中n是正整数)?在您的代码中,您在哪里使用此构造?您至少应该尝试确定错误的位置。我认为没有太多的用户会阅读您的代码,包括我自己。因此,请只发布您认为相关的部分。好吧,当您声明实例变量
n
时,您将其定义为years*12
,但此时years
是什么?ajp,非常感谢,您指出了问题,我已经纠正了。现在它的工作非常出色。谢谢。据我所知,他的付款方式是正确的。但是问题是,n
的价值并不是他所认为的,正如问题的评论所暗示的那样。谢谢你的帮助,豪斯博士和约翰,现在代码工作得很好。