jeudi 7 mai 2015

Rand function won't work as supposed in C [duplicate]

This question already has an answer here:

I want to fill a table with random numbers and calculate the time it takes to fill it.

Times seems ok but after I print the table the numbers aren't random.

It prints: 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;
}

Note: N in #define will be 30000.

I made it 10 for ease.




Aucun commentaire:

Enregistrer un commentaire