1) void srand(unsigned int seed):
*It can create a pseudo random number, if the seed is the same, then the random number is the same.
*The common way to use it is as follows:
srand((unsinged int)(time(NULL)))
As the time differs, the random number differs.
2) int rand()
*It will return a random number between 0 and RAND_MAX
*If srand(unsigned int seed) is not called befored, then the seed is set to 1 by defaut.
Example:
a, for(int i=0;i<10;i++){
ran_num=rand() % 6;
cout<<ran_num<<" ";
}
Output: 5 5 4 4 5 4 0 0 4 2
* Everytime the output remains the same.
b, srand(1);
for(int i=0;i<10;i++){
ran_num=rand() % 6;
cout<<ran_num<<" ";
}
Output: 5 5 4 4 5 4 0 0 4 2
* Everytime the output remains the same, and the same as in exp a.
c, srand(6);
for(int i=0;i<10;i++){
ran_num=rand() % 6;
cout<<ran_num<<" ";
}
Output: 4 1 5 1 4 3 4 4 2 2
* Everytime the output remains the same.
d, #include <ctime>
srand((unsigned)time(0));
for(int i=0;i<10;i++){
ran_num=rand() % 6;
cout<<ran_num<<" ";
}
Output1: 3 2 1 0 3 5 3 2 2 1
Output2: 0 1 5 2 1 0 2 4 4 2
* Everytime the output is different.
3) To create a random int number in some fixed range:
[a,b): (rand() % (b-a))+ a;
[a,b]: (rand() % (b-a+1))+ a;
(a,b]: (rand() % (b-a))+ a + 1;
Another way to get it is: a + (int)b * rand() / (RAND_MAX + 1)
4) To create a float number between 0 and 1:
rand() / double(RAND_MAX)