C++ 递归复利
我必须把它重写为递归函数,我不明白我做错了什么。我在谷歌上搜索了又搜索,看到了很多不同的方法,这让它变得更加混乱C++ 递归复利,c++,recursion,C++,Recursion,我必须把它重写为递归函数,我不明白我做错了什么。我在谷歌上搜索了又搜索,看到了很多不同的方法,这让它变得更加混乱 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 ba
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-Total(float-ir=0,int-time=0)//节省过程
{
浮球=天平;
用于(短i=0;i
我的尝试:
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);
};
float compoundit(浮动余额、浮动ir、整数时间)
{
如果(时间<0)
{
收益余额;
}
余额=余额*((1.0+ir)/时间);
返回组件(平衡,ir,--时间);
}
浮点TotalRecursive(浮点ir=0,整数时间=0)
{
返回组件(余额、ir、时间);
};
我离你很近吗?有时我只是得到了“inf”作为结果。任何帮助都将不胜感激 考虑代码的这一部分:
if (time < 0)
{
return balance;
}
因此,在上述表达式中,time
可以为零。在IEEE浮点运算中被零除会发生什么?你得到无穷大
除此之外,你还有一个bug。除以时间
,但每次递归调用时都在递减时间
。在原始函数中,您不减少时间
。因此,在递归版本中,需要将时间
和递归调用的数量作为单独的参数传递
还请注意,原始的非递归
总计也至少有两种方式被破坏,因此它也不能正确计算复利。首先,使用复利计算总余额的函数是不正确的
经过几次外观变化后,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;
}
工作代码:我看到的一个错误是,你最终会被零除,因为你停止递归不是在time
为零时,而是在它小于零时。这就解释了inf结果,我将它从1改为那只是为了看看是否会有不同的结果。谢谢有人能解释为什么我的结果如此遥远吗?很好!现在我得到了一个小的误差范围。我将时间<0替换为索引<0,并使索引值递减。结果:7年后的余额10%利息=1761.161987 7 7年后的余额10%利息=1742.000000递归计算你能解释一下总非递归方法有什么问题吗?哈哈,我真傻,它只是返回原始余额。
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);
}