CIS 150 Random numbers

Objectives

  • Generate random numbers within a given range
  • Be able to generate the same sequence or a different sequence each time the program runs

Including the required libraries

  • Include the C standard library: #include <cstdlib>
  • Include the C time library: #include <ctime>
  • No "using" statement is needed to access these libraries

Generating random numbers

  • To generate a new sequence each run, do this at the start of the program: srand(time(NULL));
  • To get a random integer: rand()
  • To get a random integer in a range from low to high: rand() % (high - low + 1) + low
  • Example for a roll of a die: rand() % (6 - 1 + 1) + 1
  • Or, shorter equivalent: rand() % 6 + 1
  • If simulating the roll of two dice, then you can't just use the range 2 through 12. The frequency would be wrong. You would have to simulate each die. Example: (rand() % 6 + 1) + (rand() % 6 + 1)