Tutorial: Generate Random Numbers

Below is the Random number tutorial outline from .tut. :)

  • Intro
    • Computers cannot generate random numbers.
    • Complex math is used instead.
    • To get the random number generated started, you need to set the random seed.
  • Setting the random seed
    • The random seed is just a number.
    • If you use a literal to set the random number, the series of random numbers will always be the same.
    • Instead, use TIMER.
  • Generating a number using only RND()
  • Using INT() to get a whole number
  • Generating a range of numbers.
#include <cstdlib>
#include <ctime>
#include <iostream>
 
using namespace std;
 
int main()
{
    srand((unsigned)time(0));
    int random_integer = rand()%10 + 1;
    cout << random_integer << endl;
    return 0;
}
  • 50 / 50 Chance
  • Simulating Dice Rolls
#include <cstdlib>
#include <ctime>
#include <iostream>
 
using namespace std;
 
int main()
{
    int random_number;
    int i;
 
    srand((unsigned)time(0));
 
    for (i=0;i<10;i++)
    {
        random_number = rand()%6 + 1;
        cout << " " << random_number << endl;
    }
    return 0;
}
  • Random array —>
  • Floats
#include <cstdlib>
#include <iostream>
#include <ctime>
using namespace std;
 
float Random()
{
    static bool seed = true;
    if ( seed )
    {
        srand(time(NULL));
        seed = false;
    }
    return (float)rand()*100 / RAND_MAX;
}
 
int main( int numArgs, char** args )
{
    for ( int i = 0; i < 5; ++i )
    {
            cout << Random() << endl;
    }
};
Categories: Tutorials
page_revision: 7, last_edited: 1245852444|%e %b %Y, %H:%M %Z (%O ago)