Rand 函数在 C 中无法正常工作

Rand function won't work as supposed in C

我想用随机数填充一个table并计算填充它所需的时间。

时间似乎还可以,但在我打印 table 之后数字不是随机的。

它打印:0 1 2 3 4 5 6 7 8 9

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 10

int  getUniqueNumber(int *p, int i);

int main()
{
    int i, p[N];
    long t0, t1, dt;

    printf("Getting %i random numbers...",N);
    time(&t0);
    for (i=0; i<N; i++)
       p[i] = getUniqueNumber(p,i);
    time(&t1);
    printf("Task Completed.\n\n");
    dt = t1 - t0;
    printf("Calc time = %ld\n",dt);

    for(i=0; i<N; i++)
       printf("%d ",i);

    return 0;
}

int  getUniqueNumber(int *p, int i)
{

    int x, j, found;
    do
    {
        srand(time(NULL));
        x = rand();
        found = 0;
        j = 0;
        while (j<=i && found == 0)
        {
            if (p[j] == x)
               found = 1;
            else
               j++;
         }
     }while (found == 1);

     return x;
}

注意:#define 中的 N 将为 30000。

为了方便,我把它设为 10。

您应该只调用 srand(time(NULL)); 一次。