請注意,如果您將每一步分解爲多個部分,可以更輕鬆地弄清楚函數的功能: (如果您的變量與源材料匹配,我發現它更容易,所以我將在我的變量的那些維基百科使用。)
// 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