C ++关于pow功能的问题

时间:2010-03-16 20:46:22

标签: c++ exponent

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

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

 return periodicPaymentcalc;
}

3 个答案:

答案 0 :(得分:9)

请注意,如果将每个步骤分成几部分,弄清楚函数正在做什么更容易: (如果您的变量与源材料匹配,我会发现它更容易,所以我会在维基百科使用的变量之后命名我的变量。)

// 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; 
} 

更容易确认此函数的逻辑是否按照这种方式执行。

如果你好奇,用我的变量名替换,你的parenthises问题如下:

  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两次,并且对两个地方使用相同的临时值,但是没有保证会发生这种情况。请注意,我们在两个函数中使用的变量数量几乎相同。我只使用了更多的命名变量,以及更少的未命名的临时变量。

答案 1 :(得分:2)

有一个错位的支架。这是一个固定版本:

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

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

答案 2 :(得分:1)

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

试试吧。我也删除了所有多余的括号,并将所有文字都改为双精度,只是为了好的措施。