C 中的尾递归

发布于 2024-09-27 15:29:20 字数 297 浏览 3 评论 0原文

我试图编写递归函数来查找数字的阶乘。

    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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

箜明 2024-10-04 15:29:20

在执行尾递归函数(尤其是尾递归函数)时,除了另一个具有更友好界面的函数之外,拥有一个辅助函数通常会很有帮助。友好的接口函数实际上只是设置不太友好的函数的参数。

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);
}

通过传递累加器值,您可以避免使用指针或在从被调用函数返回时进行任何计算,这使得函数真正成为尾递归。

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.

单挑你×的.吻 2024-10-04 15:29:20

这是带有定义的链接: http://phoenix.goucher.edu/~kelliher/ cs23/feb21.html

“如果函数所做的最后一件事是进行递归调用,则该函数是尾递归的。”

在您发布的代码中,函数所做的最后一件事是对其自身进行递归调用,因此根据这个定义,它是尾递归的。

Here's a link with a definition: http://phoenix.goucher.edu/~kelliher/cs23/feb21.html

"A function is tail recursive if the very last thing it does is make its recursive call."

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文