-1
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int dorand(){
int i;
srand(time(0));
i = rand()%3+1;
return i;
}

int main (){
printf("\n %d \n", dorand());
printf("\n %d \n", dorand());
printf("\n %d \n", dorand());
printf("\n %d \n", dorand());
return 0;
}

The issue is: the four printf are printing the same number. When I do the rand() directly in the main function there is no problem at all but when I call a function to do so the random generation gets addicted to the same number. Do someone have some experience to share, please?

I've tried:

int main (){
srand(time(0)) //seeding in the main function before calling the dorand function
printf("\n %d \n", dorand());
printf("\n %d \n", dorand());
printf("\n %d \n", dorand());
printf("\n %d \n", dorand());
return 0;
}

Also

int dorand(){
int i;
i = 0; //clearing the variable before attributing a new rand value
srand(time(0));
i = rand()%3+1;
return i;
}

Sorry if I mistook something, thanks for helping

1 Answers1

0

The srand function seeds the random number generator. For a given seed value, the same set of random numbers gets generated.

Since you re-seed each time you want a random number, using the current time as the seed, assuming each call to the function happens in the same second the random number function is seeded with the same value, so you keep getting the same "random" numbers.

You should call srand only once at the beginning of your program. Remove the call from dorand and put it at the top of main.

dbush
  • 205,898
  • 23
  • 218
  • 273