Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random numbers in C

Tags:

c

random

srand

for(i = 0; i < n; i++){
        srand(time(NULL));
        printf("%d ", time(NULL));
        for(j = 0; j < (n-1); j++){
            a[i][j] = rand();
        }
    }

I try to generate random numbers, but they are the same... I try srand(i * time(NULL)). No matter.. What should i do?

Array declaration:

int** a;
int i;
printf("Enter array size: ");
scanf("%d", &n);

a = (int**)calloc(n, sizeof(int));
for(i = 0; i < n; i++)
    a[i] = (int*)calloc(n-1, sizeof(int));
like image 787
Sergey Gavruk Avatar asked Mar 15 '10 18:03

Sergey Gavruk


People also ask

What is random number in C language?

Description. The C library function int rand(void) returns a pseudo-random number in the range of 0 to RAND_MAX. RAND_MAX is a constant whose default value may vary between implementations but it is granted to be at least 32767.

What library is rand () in C?

The rand function, declared in stdlib. h, returns a random integer in the range 0 to RAND_MAX (inclusive) every time you call it. On machines using the GNU C library RAND_MAX is equal to INT_MAX or 231-1, but it may be as small as 32767.


1 Answers

Call srand() outside of the loop. You are reseeding it every iteration.

srand() seeds the random number generator so you get a different sequence of random numbers depending on the input. Your loop runs very fast, so the call to time(NULL) always returns the same value. You are resetting to the same random sequence with every iteration. As a general rule, only call srand() once in your program.

like image 160
Byron Whitlock Avatar answered Sep 20 '22 07:09

Byron Whitlock