请注意,如果您将每个步骤分解成多个部分,那么弄清楚函数在做什么会变得多么容易:(如果您的变量与源材料匹配,我发现它会更容易,因此我将在 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
在你的函数中使用了两次,并在两个地方使用相同的临时,但不能保证这会发生。请注意,我们在两个函数中使用了几乎相同数量的变量。我只是使用了更多的命名变量,以及更少的未命名的临时变量。