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
Seeding the generator should be done once(for each sequence of random numbers you want to generate of course!):
#include <stdio.h>
#include <stdlib.h>
int main()
{
int seed = time(NULL);
srand(seed);
int value = 0;
int i=0;
for (i=0; i< 5; i++)
{
value =rand();
printf("value is %d\n", value);
}
}
Move the srand()
call into main()
, before the loop.
In other words, call srand()
once and then call rand()
repeatedly, without any further calls to srand()
:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int value = 0;
int i = 0;
srand(time(NULL));
for (i = 0; i < 5; i++)
{
value = rand();
printf("value is %d\n", value);
}
}
If you want to reseed (for extra randomness) every time you call random()
, here's one way you could do that:
srandom( time(0)+clock()+random() );
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 of clock()
Of course you could do more if you really, really, want randomness -- but this is a start.
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
Try this:
#include <stdio.h>
#include <time.h>
int main(void) {
for (int i = 0; i < 10; i++) {
printf("%ld\n", (long)time(NULL));
}
}
My "guess" is that 10 equal values will be printed :)