2017-06-09 49 views
0

我必須將其重寫爲一個遞歸函數,並且我不明白我在做什麼錯誤。我搜索並搜索了很多不同的方式,這使得它更加令人困惑。遞歸複利興趣

float Total(float ir=0, int time=0)//Savings Procedure 
{ 
    float bal = Balance; 
    for (short i = 0; i < time; i++) 
    { 
     bal += (Balance*((1.0+ir)/time))/100; 
    } 
    return bal; 
}; 

我嘗試:

float compoundit(float balance, float ir, int time) 
{ 
    if (time < 0) 
    { 
     return balance; 
    } 
    balance = balance * ((1.0 + ir)/time); 
    return compoundit(balance, ir, --time); 
} 
float TotalRecursive(float ir=0, int time=0) 
{ 
    return compoundit(Balance, ir, time); 
}; 

難道我還差得遠?有時我會因此而得到'inf'。任何幫助,將不勝感激。

+0

一個錯誤,我看到的是你會最終除以零,因爲你停止遞歸不是'時間'是零但是當它小於零。 –

+0

這解釋了inf的結果,我將它從1改爲了只是爲了看看是否會有不同的結果。謝謝。任何人都可以解釋爲什麼我的結果如此遙遠? –

回答

0

首先,您使用複利計算總餘額的函數是不正確的。

夫婦的化妝品的變化後,TT應該是:

float computeIterative(float Balance, float ir=0, int time=0) 
{ 
    // The total balance is same as the initial balance if 
    // time is zero. 
    float bal = Balance; 
    for (int i = 0; i < time; i++) 
    { 
     // Compute the interest for this period 
     float interest = bal*ir/100; 

     // Add the interest to the balance so the interest 
     // for the next period is a compound interest. 
     bal += interest; 
    } 

    // The total balance after all the interests have 
    // been compounded. 
    return bal; 
} 

該函數的遞歸版本應該是:

float computeRecursive(float Balance, float ir=0, int time=0) 
{ 
    if (time == 0) 
    { 
     return Balance; 
    } 

    float interest = Balance * ir/100; 
    return computeRecursive(Balance + interest, ir, time-1); 
} 

工作代碼:http://ideone.com/W5ExPT

0

考慮你的這部分代碼:

if (time < 0) 
{ 
    return balance; 
} 

好吧,在這一點上,我們知道time >= 0。 Next:

balance = balance * ((1.0 + ir)/time); 

所以time在上述表達式中可以爲零。當你在IEEE浮點除以零時會發生什麼?你得到無限。

除此之外,你還有一個錯誤。除以time,但在每次遞歸調用時遞減time。在原始函數中,您不會減少time。因此,在遞歸版本中,您需要將time和您所做的遞歸調用數作爲單獨的參數傳遞。

還要注意,原始非遞歸Total也至少在兩種方式中被破壞,所以它也沒有正確地計算複利。

+0

不錯!現在我得到一個小的誤差。我將時間<0替換爲索引<0,並使索引值遞減。結果:7年後餘額10%利息= 1761.161987 7年後餘額10%利息= 1742.000000遞歸計算 –

+0

你能解釋一下總非遞歸方法有什麼問題嗎? –

+0

哈哈,我很愚蠢,它只是恢復原來的平衡。 –