Reputation: 3833
I am trying to understand the random-generating-function in c.
For what I read the random number returned by the function is dependent on its initial value, called a seed that remains the same for each run of a program. This means that the sequence of random numbers that is generated by the program will be exactly the same on each run of the program.
So this is solved by using another function- srand(seed) - which will use a different seed value on every run, causing a different set of random values every run. And to seed this random number generator with a arbitrary value the System clock could be used. So in summary: the time is used as a seed value.
So after implementing the srand(seed)-function the random number generating reallt worked fine, BUT - what i do not understand is that the seed value is always the same. I thought the whole idea about seeding the random number generator was to use a new seed-value every time the program executes. But in the console-window in Eclipse the seed-value seems to be the same everytime, i. e. 4071056, 4071056, 4071056, 4071056, 4071056, 4071056
and the random numbers generated for instance: 1,6,5,5,1,4
Got the information from http://www.cprogramming.com/tutorial/random.html
EDIT: *Think I understand it now. In java it would be a missmatch error between int and void,
int t = srand(time(NULL));
printf("seed value: %d \n", t);
int rand_nmbr = (rand() % 6 + 1);
printf("dice face: %d ", rand_nmbr);
Upvotes: 1
Views: 418
Reputation: 123458
srand
doesn't return a value; its prototype is
void srand(unsigned int seed);
assigning the (non-existent) result of srand
to t
is a coding error; you're just printing out garbage.
If you want to see the actual value of the seed use
time_t t;
time(&t);
srand(t);
Upvotes: 4
Reputation: 106012
srand()
function is of void
type which returns nothing. Your compiler should give error for this
[Error] void value not ignored as it ought to be
calling a void
function by assigning it to a variable is wrong.
Upvotes: 0