I wrote this C code below, when I loop, it returns a random number. How can I achieve the 5 different random values if myrand() is executed?
#include <stdio.h>
#include <stdlib.h>
int myrand() {
int ue_imsi;
int seed = time(NULL);
srand(seed);
ue_imsi = rand();
return ue_imsi;
}
int main()
{
int value = 0;
int i=0;
for (i=0; i< 5; i++)
{
value =myrand();
printf("value is %d\n", value);
}
}
The point of seed() is to start the sequence of random numbers with a known value,
you will then always get the same sequence of numbers given the same seed.
This is why you have seed(), it both allows you to generate the same sequence for testing, or given a random seed (typically the time) you get a different sequence each time
Seeding the generator should be done once(for each sequence of random numbers you want to generate of course!):
Move the
srand()
call intomain()
, before the loop.In other words, call
srand()
once and then callrand()
repeatedly, without any further calls tosrand()
:If you want to reseed (for extra randomness) every time you call
random()
, here's one way you could do that:time()
updates once per second, but will be different every time you run your programclock()
updates much more frequently, but starts at 0 every time you run your programrandom()
makes sure that you (usually) don't reseed with the same value twice in a row if your loop is faster than the granularity ofclock()
Of course you could do more if you really, really, want randomness -- but this is a start.
Try this:
My "guess" is that 10 equal values will be printed :)