The only way (that I am aware of) to generate random numbers in C/C++ is the following.
Random numbers in C/C++ are pretty crude. There is nothing like rand.next(1, 100).
Instead, the use of the
rand() and
srand() functions are invloved.
CODE
#include <cstdlib>
#include <ctime>
#include <iostream>
using namespace std;
int main() {
srand(time(NULL));
cout << rand() % 10 + 1 << endl; //number between 1 and 10
return 0;
}
Lets go through this. First we use the
srand() function to
seed the randomizer. Basically, the computer can generate random numbers based on the number that is fed to
srand(). If you gave the same seed value, then the same random numbers would be generated every time.
Therefore, we have to seed the randomizer with a value that is always changing. We do this by feeding it the value of the current time with the
time() function.
Now, when we call rand(), a new random number will be produced every time.
CODE
#include <ctime>
#include <cstdlib>
#include <iostream>
using namespace std;
int main() {
srand(time(NULL));
cout << rand() << endl;
return 0;
}
The previous code gives me numbers like 113848035.
Although this is a random number, we need to do something to reduce it to a given range.
This is accomplished by applying the modulus operator (% in most languages) to the number.
Any number "modded" by 3 will either be 0, 1, or 2.
If we want a number from 0 to 9, we would write
CODE
rand() % 10;
while adding 1 would give us 1 to 10;
CODE
rand() % 10 + 1;
The reader should now understand how to generate random numbers.