9.1 函数:尾递归计算阶乘(factorial)

最简单的递归形式就是把递归调用置于函数的末尾,即正好在return语句之前,这种形式的递归被称为尾递归 (tail recursion),其形式相当于循环。

/* 递归计算阶乘 */
#include
long fact(int n);
long rfact(int n);
int main()
{
    int num;
    printf("this program calculates factorials.\n");
    printf("enter a value in the range 0-12(q to quit): \n");
    while (scanf("%d", &num) == 1) //输入验证,scanf()函数不读换行符
    {
        if (num < 0)
            printf("no negative numbers, please.\n");
        else if (num > 12)
            printf("keep intput under 13.\n");
        else
        {
            printf("loop: %d factorial = %ld\n",num,fact(num));
            printf("recursion: %d factorial = %ld\n", num, rfact(num));
        }
        printf("enter a value in the range 0-12 (q to quit):\n");
    }
    printf("bye.\n");
    return 0;
}
long fact(int n)   //循环函数
{
    long ans;
    for (ans = 1; n > 1; n--)
        ans *= n;
    return ans;
}
long rfact(int n)   //递归调用
{
    long ans;
    if (n > 0)
        ans = n*rfact(n - 1);
    else
        ans = 1;
    return ans;
}

你可能感兴趣的:(9.1 函数:尾递归计算阶乘(factorial))