< Previous | Contents | Next >

Introducing the Die Roller

Program

The Die Roller program simulates the roll of a six-sided die. The computer calculates the roll by generating a random number. Figure 2.12 shows the results of the program.

You can download the code for this program from the Course Technology website (www.courseptr.com/downloads). The program is in the Chapter 2 folder; the filename is die_roller.cpp.

// Die Roller

// Demonstrates generating random numbers


#include <iostream> #include <cstdlib> #include <ctime>


using namespace std;

Generating Random Numbers 69


image

Figure 2.12

The die roll is based on a random number generated by the program.


int main()

{

srand(static_cast<unsigned int>(time(0))); //seed random number generator int randomNumber = rand(); //generate random number

int die = (randomNumber % 6) + 1; // get a number between 1 and 6 cout << "You rolled a " << die << endl;


return 0;

}