Author : Roman K.
Page : 1
The Problem
Well as you may know rand() returns the next pseudo-random number in the series. The default seed for the series is 1. You can change it by calling srand().But calling srand() doesn’t always mean that you will get “real” random numbers.For example the following code looks like it would return random numbers but it does not:
#include <stdlib.h> /* header for rand() and srand() */
#include <stdio.h> /* io header */
int main()
{
srand(rand());
for(int i=0;i<=9;i++)
printf(“%i\n”,rand());
return 0;
}
The output of this program will be the same each time you run it. Feel free to test this.
Solution
As mentioned above srand() can be used to change the seed. But if you set it to a constant the series would still be the same. So we use srand(time(0)). time() returns a time_t object. You can interpret it as an integer and the value will always differ. So, now we would have:
#include <stdlib.h> /* header for rand() and srand() */
#include <stdio.h> /* io header */
#include <time.h> /* header needed for time() */
int main()
{
srand(time(0));
for(int i=0;i<=9;i++)
printf(“%i\n”,rand());
return 0;
}
Now we have real random numbers.
Contact
If you have any questions/comments e-mail me at r0m4n@yahoo.com
I hope you enjoyed this tutorial, and have a nice day.
Page : 1