Monday, October 10, 2011

rand() and srand()

Sometimes you need to generate a random number. In C++, the easiest way to do this is to invoke the rand() function from the cmath library. This method returns a value from [0 - 32767] but you can use a little mathematical

Here are some examples and what they return:
  • Code: (rand() % 10)
    Returns: [0 -   9]

  • Code: (rand() % 10) + 1
    Returns: [1 -  10]

  • Code: (rand() % 100)
    Returns: [0 -  99]

  • Code: (rand() % 100) + 1
    Returns: [1 - 100]


Addendum
To make your random numbers more random, you can seed the srand() function with time. Before using one of the constructions above, execute this code:

srand(time(NULL));