执行时C中的递归阶乘程序挂起 [英] Recursive factorial program in C hangs when executing

查看:46
本文介绍了执行时C中的递归阶乘程序挂起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm writing a program to display the time needed to calculate a factorial of a given number 2 million times. I'm writing it using Debian Linux in the C/C++ Eclipse environment. When the program gets to int temp = n * rfact(n-1);, it hangs and won't do anything else.

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

Here's what I've got so far:

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

推荐答案

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

You are missing the base case, so you are running into an infinite recursion. You need to stop when you get to n == 1 or n == 0:

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

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

Also, the factorial function is not really the best use case for recursion because the iterative version is arguably more readable and possibly a lot faster, but that's a different story :)

这篇关于执行时C中的递归阶乘程序挂起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆