请注意,如果您将每一步分解为多个部分,可以更轻松地弄清楚函数的功能: (如果您的变量与源材料匹配,我发现它更容易,所以我将在我的变量的那些维基百科使用。)
// 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;
}
或许有一些优化的编译器会使用它,比如注意到它在你的函数中使用了两次,并且在两个地方使用了相同的临时文件,但是这不会发生。请注意,我们在两个函数中都使用了几乎相同数量的变量。我只使用了更多的命名变量,以及更少的未命名的临时变量。
如果你把计算分成更小的步骤,它可能会更具可读性吗? – 2010-03-16 20:48:17
请提供您收到的错误/不当行为。 – 2010-03-16 20:48:36
它以什么方式不起作用?编译错误?运行时错误的结果?运行时错误?如果这是一个错误,请发布错误。另外,我们可能需要知道所有这些变量的类型。 – 2010-03-16 20:49:03