This question already has an answer here:
- srand() — why call it only once? 7 answers
I am making a simple example in C with rand() but the function always return the same number despite i am using srand().
This is the code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int generate(int min, int max)
{
srand(time(NULL));
return rand() % (max - min + 1) + min;
}
int main()
{
int i;
for (i = 0; i < 10; i++)
{
printf("Number random %d = %d\n", i, generate(1, 100));
}
return 0;
}
Execution :
Number random 0 = 40 Number random 1 = 40 Number random 2 = 40 Number random 3 = 40 Number random 4 = 40 Number random 5 = 40 Number random 6 = 40 Number random 7 = 40 Number random 8 = 40 Number random 9 = 40