【问题标题】:Recursive factorial program in C hangs when executingC中的递归阶乘程序在执行时挂起
【发布时间】:2013-02-10 02:14:58
【问题描述】:

我正在编写一个程序来显示计算给定数字的阶乘 200 万次所需的时间。我在 C/C++ Eclipse 环境中使用 Debian Linux 编写它。当程序到达int temp = n * rfact(n-1); 时,它会挂起并且不会执行任何其他操作。

这是我目前得到的:

#include <stdio.h>
#include <time.h>

//prototypes
int rfact(int n);

main()
{
    int n = 0;
    int i = 0;
    double result = 0.0;
    clock_t t;
    printf("Enter a value for n: ");
    scanf("%i", &n);

printf("n=%i\n", n);

    //get current time
    t = clock();

    //process factorial 2 million times
    for(i=0; i<2000000; i++)
    {
        rfact(n);
    }

    printf("n=%i\n", n);

    //get total time spent in the loop
    result = (clock() - t)/(double)CLOCKS_PER_SEC;

    //print result
    printf("runtime=%d\n", result);
}

//factorial calculation
int rfact(int n)
{
    int temp = n * rfact(n-1);
    printf(i++);
    return temp;
}

【问题讨论】:

    标签: c eclipse recursion factorial


    【解决方案1】:

    您缺少基本情况,因此您遇到了无限递归。到达n == 1或n == 0时需要停下来:

    int rfact(int n)
    {
        if (n <= 0)
            return 1;
        return n * rfact(n-1);
    }
    

    此外,阶乘函数并不是递归的最佳用例,因为迭代版本可以说更具可读性并且可能更快,但这是另一回事 :)

    【讨论】:

      【解决方案2】:

      您的 rfact 函数中没有基本情况。这意味着 rfact(n-1) 将永远被调用。

      【讨论】:

        【解决方案3】:

        我同意我上面的人,你错过了递归的基本情况

        但请注意执行 2'000'000 次阶乘,除了需要花费大量时间来终止计算之外,您的变量将溢出

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-10-22
          • 1970-01-01
          • 2013-09-18
          • 1970-01-01
          • 2011-01-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多