Today a tiny tutorial to see how using srand() and rand() from the libc.
We will generate a number in a range between 0 and 2.
For that, we will use the functions:
The time() function because we want a random number that changes every second.
We will use it with the sleep() function.
We put a seed, generated by the time() function), into the srand() one.
Then we display this number with the rand() function.
And as we want a number between 0 and 2, we use the modulo operator (%).
Let's see it in details with this srand() / rand() example:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
int main (int argc, char *argv[])
{
int seed;
int i;
i = 0;
seed = time(NULL);
srand(seed);
while (i < 5)
{
sleep(1);
printf("rand[%d]= %d\n", i, rand() % 3);
++i;
}
return 0;
}$ rand[0]= 2
Comments
Anonymous (not verified)
Tuesday, March 29, 2016 - 12:24pm
Permalink
hii this solution is useful
hii this solution is useful
Add new comment