-
Random number generator
Ok I seem to have a further problem, with the rand function. It produces the same set of random numbers in the same order every time it get's called. Now if I use the srand(time(NULL)) to create a different seed every time. The time function seems to return the same number every time and therefore produce the same random number every time.
Code:
#include <stdlib.h>
char* LB_Random(char *maxR,char *dummy)
{
int i;
static char n[10];
int rMax = atoi(maxR);
rMax++;
i = rand() % rMax;
sprintf(n,"%d",i);
return n;
}
The above produces: 9,3,14,4,1,12,6,14 everytime
Code:
#include <stdlib.h>
char* LB_Random(char *maxR,char *dummy)
{
int i;
static char n[10];
int rMax = atoi(maxR);
rMax++;
srand(time(NULL));
i = rand() % rMax;
sprintf(n,"%d",i);
return n;
}
Produces the number 5 everytime, due to the time function returning the same number.
-
Well here - http://cboard.cprogramming.com/showthread.php?t=85926
You first got it wrong, how to do it right was explained and then you got it right yourself.
Now you've regressed back into doing it wrong again.
> srand(time(NULL));
This line goes at the start of main.
You do it exactly once in the program.
-
srand() should only be called once. Do it outside the function or keep a static boolean variable that knows whether or not srand() has been called.
-
Ok let me try and explain this a bit better. I'm using a piece of software which will take a C header file and an obj file, import these as extra functionality and then it can call the functions these have defined so it's something like this.
Code:
INCLUDE(random)
while(not_eof)
{
call(random,"15")
go to next line
}
The 15 represents the maximum random number, now my header file looks like this
Code:
extern char* LB_Random(char*,char*);
And as you know my main code looks like this
Code:
char* LB_Random(char *maxR,char *dummy)
{
int i;
static char n[10];
int rMax = atoi(maxR);
rMax++;
i = rand() % rMax;
sprintf(n,"%d",i);
return n;
}
Seeing as you say I can only call srand once ever, what should I do. The only thing i can think of is defining another function in the above code that seeds during initialisation, and then calling the random function over and over. So something like
Code:
//Init
INCLUDE(random)
call(seed,"")
while(not_eof)
{
call(random,"15")
go to next line
}
How's that sound.
-
-