C中的递归因子程序在执行时挂起

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

这是我到目前为止所得到的:

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

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

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

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

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

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

但要注意做一个2’000’000次因子,你的变量会因为花费大量时间来终止计算而溢出