我正在尝试编写递归函数,以查找数字的阶乘。
int factorial(int input,int *answer)
{
if ( input ==0 )
{
return 0;
}
*answer = *answer * input;
factorial(input -1, answer);
}
您对这个功能有什么看法?这是尾递归吗?
答案 0 :(得分:6)
当执行尾递归函数(尤其是尾递归函数)时,除了具有更友好接口的另一个函数之外,还有一个辅助函数通常是有帮助的。友好的接口函数实际上只是设置了不太友好的函数的参数。
static unsigned factorial_helper(unsigned input, unsigned acc) {
if (intput == 0) {
return acc;
}
return factorial_helper(input-1, acc * input);
}
unsigned factorial(int input) {
if (input < 0) {
do_something_bad();
}
return factorial_helper(input, 1);
}
通过传递一个累加器值,你可以避免在从被调用函数返回时使用指针或进行任何计算,这使得函数真正地是尾递归的。
答案 1 :(得分:4)
以下是定义的链接:http://phoenix.goucher.edu/~kelliher/cs23/feb21.html
“如果函数最后做的是进行递归调用,则函数是尾递归的。”
在你发布的代码中,函数做的最后一件事就是对它自己进行递归调用,所以通过这个定义,它是尾递归的。