Full Version: Producing Random Numbers
Dream.In.Code > Programming Tutorials > C++ Tutorials
Jessehk
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.
Videege
I would suggest a small paragraph explaining the actual meaning of the modulus operator as a whole rather than its specific use in obtaining random numbers within a certain range (i.e., users should learn the logic of the operator and not simply that "it makes this range").

Also, if you want to take it to the next level, you could add sections explaining the process of random number generation (i.e. what is going on when you call rand()) as well as alternative number generation algorithms (for advanced users who wish to write their own methods for whatever reason).


Good start!
born2c0de
Nice Tutorial for beginners.
As Videege said...I think you should go ahead with a more advanced tutorial on Random Numbers next.
Cheers.
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Invision Power Board © 2001-2008 Invision Power Services, Inc.