C 中的尾递归
我试图编写递归函数来查找数字的阶乘。
int factorial(int input,int *answer)
{
if ( input ==0 )
{
return 0;
}
*answer = *answer * input;
factorial(input -1, answer);
}
对于这个功能你有什么想说的吗?是尾递归吗?
I was trying to write recursion function,to find factorial of a number.
int factorial(int input,int *answer)
{
if ( input ==0 )
{
return 0;
}
*answer = *answer * input;
factorial(input -1, answer);
}
What will you say about this function? Is it tail recursive?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在执行尾递归函数(尤其是尾递归函数)时,除了另一个具有更友好界面的函数之外,拥有一个辅助函数通常会很有帮助。友好的接口函数实际上只是设置不太友好的函数的参数。
通过传递累加器值,您可以避免使用指针或在从被调用函数返回时进行任何计算,这使得函数真正成为尾递归。
When doing tail recursive functions (especially tail recursive functions) it is often helpful to have a helper function in addition to another function which has a more friendly interface. The friendly interface function really just sets up the less friendly function's arguments.
By passing an accumulator value you avoid having to use pointers or do any computations upon returning from called functions, which makes the functions truely tail recursive.
这是带有定义的链接: http://phoenix.goucher.edu/~kelliher/ cs23/feb21.html
在您发布的代码中,函数所做的最后一件事是对其自身进行递归调用,因此根据这个定义,它是尾递归的。
Here's a link with a definition: http://phoenix.goucher.edu/~kelliher/cs23/feb21.html
In the code you posted, the last thing the function does is make a recursive call to itself, so by this definition, it is tail-recursive.