用C尾递归 [英] Tail recursion in C
问题描述
我试图写递归函数,找到了一些阶乘。
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?
推荐答案
在做尾递归功能(特别是尾递归函数)往往是有帮助的,除了它有一个更友好的界面其它功能的辅助函数。友好的界面功能其实只是设置了不太友好的函数的参数。
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.
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);
}
通过传递,您就不必在从调用的函数返回,这使得功能忠实地尾递归使用指针或做任何计算的累加值。
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.
这篇关于用C尾递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!