I'll try to explain rand / srand for you. When dealing with computers there is no
such thing as random numbers. The rand function just takes a base number runs it
through a complex algorithm and the result appears to be random but if you
new the base number and the algorithm you could predict the result.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
int main()
{
cout << "Random numbers: ";
int random = 0;
for (int i = 0; i < 5; i++)
{
random = rand();
cout << random << ',' << ' ';
}
cin.ignore();
return 0;
}
|
run this program a couple of times and you will see that you always get the same numbers
this is because the base number and the algorithm are the same.
This is where srand() comes in. srand allows us to change the base number.
this in turn gives us differant results.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
srand(0); //<<-------------------------change this number
int random = 0;
cout << "Random numbers #: ";
for (int i = 0; i < 5; i++)
{
random = rand();
cout << random << ',' << ' ';
}
cin.ignore();
return 0;
}
|
run this program a couple of times change the base number after each run you will
see that you get differant results each time.
Unfortunatly for every base number you will get the same results every time you
run the program. So to get differant results you need to keep changing the base number.
Usually this is done by using this statement srand(time(NULL)); Honestly i forget
what time(NULL) does exactly, but it evaluates to a number and this number is based
on time. Since time is constantly changing the number it evaluates to is also constantly changing.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
Example
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand(time(NULL));
int random = 0;
cout << "Random numbers #: ";
for (int i = 0; i < 5; i++)
{
random = rand();
cout << random << ',' << ' ';
}
cin.ignore();
return 0;
}
|
try running this code and you will see what I mean.
i Do that, but then it says too few arguments for srand(). how do i use it, and do i need an #include for it? |
srand takes an unsigned integer and is in the <cstdlib> header file
time is in the <ctime> header file