2013-02-25 59 views
1

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

这里是我到目前为止有:

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

回答

5

你缺少的基本情况,所以你正在运行到一个无限递归。你需要停下来,当你到n == 1n == 0

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

此外,阶乘函数是不是真的是最好的使用情况递归因为迭代版本更易读,并可能快了很多,但是这是一个不同的故事:)

1

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

1

我的人我同意上述,你缺少递归

的基本情况,但要注意做一个阶乘2'000'000时代,你的变量将开去溢出服用大量的时间计算被终止

+0

哦哇大facepalm那里有一个好点 – zakparks31191 2013-02-25 01:19:58