递归复利

Recursive Compounding Interest

本文关键字:递归      更新时间:2023-10-16

我必须将其重写为递归函数,我不明白我做错了什么。我用谷歌搜索了又用谷歌搜索,看到了许多不同的方式,这只会让它更加混乱。

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"。任何帮助将不胜感激。

首先,您使用复利计算总余额的函数不正确。

经过几次外观更改后,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

考虑代码的这一部分:

if (time < 0)
{
    return balance;
}

好的,在这一点上我们知道time >= 0.下一个:

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

因此,time在上面的表达式中可以为零。当你在IEEE浮点数中除以零时会发生什么?你得到无限。

除此之外,您还有另一个错误。你除以time,但你在每个递归调用上递减time。在原始函数中,您不会递减time .因此,在递归版本中,您需要将time和您进行的递归调用的数量作为单独的参数传递。

另请注意,原始的非递归Total也至少以两种方式被破坏,因此它也没有正确计算复利。