C++关于pow功能的问题

Sag*_*tic 1 c++ exponent

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

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

 return periodicPaymentcalc;
}
Run Code Online (Sandbox Code Playgroud)

Bil*_*ill 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; 
} 
Run Code Online (Sandbox Code Playgroud)

确认此函数的逻辑以这种方式执行它应该更容易.

如果你很好奇,用我的变量名替换,你的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
Run Code Online (Sandbox Code Playgroud)

通过这种分组,你只传递一个参数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; 
} 
Run Code Online (Sandbox Code Playgroud)

我的也将被打破,看起来像:

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; 
} 
Run Code Online (Sandbox Code Playgroud)

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