递归复利
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
也至少以两种方式被破坏,因此它也没有正确计算复利。
相关文章:
- 通过递归进行因子分解
- 递归函数计算序列中的平方和(并输出过程)
- 使用递归的数组的最小值.这是怎么回事
- 递归列出所有目录中的C++与Python与Ruby的性能
- 递归计数给定目录的文件和所有目录
- 如何在BST的这个简单递归实现中消除警告
- C++:正在检查LinkedList中的回文-递归方法-错误
- 递归模板化函数不能分配给具有常量限定类型"const tt &"的变量"state"
- 递归无序映射
- TSP递归解的迭代形式
- 如何在Elixir中调用递归函数并行
- 返回递归调用和仅递归调用的区别
- 数组元素打印的递归方法
- 使用递归时获取变量的奇怪值
- 如何在C++中递归地按相反顺序打印集合
- 到连接组件算法的问题(递归)
- 如何使用递归打印修改后的星号三角形图案
- 使用递归模板动态分配的多维数组
- 递归函数有效,但无法记忆
- 包含模板文件的递归会导致编译失败