我必须将其重写为递归函数,我不明白我做错了什么。我用谷歌搜索和谷歌搜索,看到了许多不同的方式,这让它更加混乱。
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)
考虑这部分代码:
if (time < 0)
{
return balance;
}
好的,此时我们知道time >= 0
。下一个:
balance = balance * ((1.0 + ir)/time);
所以time
在上面的表达式中可能为零。当你在IEEE浮点数中除以零时会发生什么?你得到无限。
除此之外,还有另一个错误。除以time
,但每次递归调用都会递减time
。在原始函数中,您不会递减time
。因此,在递归版本中,您需要将time
和您所做的递归调用的数量作为单独的参数传递。
另请注意,原始非递归Total
也至少在两种方式中被破坏,因此它也无法正确计算复合兴趣。
答案 1 :(得分:0)
首先,使用复利计算总余额的函数不正确。
经过几次化妆品改变,应该是:
@EnableJpaRepositories(repositoryFactoryBeanClass = EnversRevisionRepositoryFactoryBean.class, repositoryBaseClass = CustomPagingAndSortingRepositoryImpl.class)
该函数的递归版本为:
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;
}