0

以下のコードは、forループの秒単位でランタイムを見つける必要があります。他のリソースを見ると、これでうまくいくはずですclock()。forclock()ループの実行後に最初のサブプラクティスが実行されます。コードが記述どおりに機能しない理由はありますか?

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

それ以外の場合は、整数除算を実行し、結果をdoubleに変換しますが、これは目的ではありません。

また:

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

する必要があります:

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