1

我试图让这个表达式起作用,我很确定它不是括号,因为我计算了所有这些。也许我做错了涉及参数 pow (x,y)。

double calculatePeriodicPayment()
{
 periodicPaymentcalc = (loan * ((interestRate / yearlyPayment)))  / (1-((pow ((1+(interestRate / yearlyPayment)))),(-(yearlyPayment * numOfYearLoan))));

 return periodicPaymentcalc;
}
4

3 回答 3

9

请注意,如果您将每个步骤分解成多个部分,那么弄清楚函数在做什么会变得多么容易:(如果您的变量与源材料匹配,我发现它会更容易,因此我将在 Wikipedia 使用的变量之后命名我的变量。 )

// amortization calculator
// uses annuity formula (http://en.wikipedia.org/wiki/Amortization_calculator)
// A = (P x i) / (1 - pow(1 + i,-n))
// Where:
//   A = periodic payment amount
//   P = amount of principal
//   i = periodic interest rate
//   n = total number of payments
double calculatePeriodicPayment()
{ 
  const double P = loan;
  const double i = interestRate / yearlyPayment;
  const double n = yearlyPayment * numOfYearLoan;

  const double A = (P * i) / (1 - pow(1.0 + i, -n));

  return A; 
} 

确认这个函数的逻辑以这种方式完成了它应该做的事情要容易得多。

如果你很好奇,把我的变量名代入,你的括号问题如下:

  const double A = (P * i) / (1 - pow(1 + i)), -n; // <- this is how you have it
  const double A = (P * i) / (1 - pow(1 + i, -n)); // <- this is how it should be

通过这种分组,您只需将一个参数传递给pow,这就是编译器说no overloaded function takes 1 arguments.

编辑:你提到我使用了更多变量。但是,您的编译器将像我一样使用临时变量。您的复杂语句将被分解成多个部分,可能看起来像这样:

double calculatePeriodicPayment() 
{
  const double temp1 = interestRate / yearlyPayment;
  const double temp2 = loan * temp1;
  const double temp3 = interestRate / yearlyPayment;
  const double temp4 = 1.0 + temp3;
  const double temp5 = yearlyPayment * numOfYearLoan;
  const double temp6 = -temp5;
  const double temp7 = pow(temp4, temp5);
  const double temp8 = 1 - temp7;
  const double temp9 = temp2 / temp8;

  periodicPaymentcalc = temp9; 
  return periodicPaymentcalc; 
} 

我的也会被分解,看起来像:

double calculatePeriodicPayment()
{ 
  const double P = loan;
  const double i = interestRate / yearlyPayment;
  const double n = yearlyPayment * numOfYearLoan;

  const double temp1 = P * i;
  const double temp2 = 1.0 + i;
  const double temp3 = -n;
  const double temp4 = pow(temp2, temp3);
  const double temp5 = 1 - temp4;
  const double temp6 = temp1 / temp5;
  const double A = temp6;

  return A; 
} 

也许编译器会使用一些优化,例如注意到它interestRate / yearlyPayment在你的函数中使用了两次,并在两个地方使用相同的临时,但不能保证这会发生。请注意,我们在两个函数中使用了几乎相同数量的变量。我只是使用了更多的命名变量,以及更少的未命名的临时变量。

于 2010-03-16T21:30:25.257 回答
2

有一个错位的括号。这是一个固定版本:

periodicPaymentcalc = (loan * ((interestRate / yearlyPayment))) / (1 - ((pow ((1+(interestRate / yearlyPayment)),(-(yearlyPayment * numOfYearLoan))))));

使用高亮匹配括号的编辑器来避免此类错误。或者只是创建临时变量来保存中间值。

于 2010-03-16T20:50:28.020 回答
1
periodicPaymentcalc = (loan * interestRate / yearlyPayment) /
  (1.0 - pow (1.0 + interestRate / yearlyPayment, -yearlyPayment * numOfYearLoan));

试试看。我也删除了所有多余的括号,并将所有文字更改为双精度值,只是为了更好地衡量。

于 2010-03-16T20:57:57.503 回答