0

下面的代码应该在 for 循环的几秒钟内找到运行时。查看其他资源,这应该可以解决问题,在 for 循环运行后clock()从 a 中减去初始值。clock()任何想法为什么代码不能按书面方式工作?

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

//prototypes
int rfact(int n);
int temp = 0;

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 = (double)((clock() - t)/CLOCKS_PER_SEC);

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

//factorial calculation
int rfact(int n)
{

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

1 回答 1

2
result = (double)((clock() - t)/CLOCKS_PER_SEC);

这应该是:

result = ((double)(clock() - t))/CLOCKS_PER_SEC;

否则,您将进行整数除法并将结果转换为双精度数,这不是您想要的。

还:

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

应该:

printf("runtime=%f\n", result);
于 2013-02-25T00:58:02.300 回答