STOP PRESS! The full book is now available DIRECTLY from Amazon with lower shipping costs!
This program uses a do-while loop to repeatedly roll a pair of dice. The loop terminates once a double has been rolled. Each roll is simulated by calling the roll6sided() function.
Select and copy the C++ source-code at the bottom of this post.
Paste into a text editor, such as Nano or Geany.
Then save the new file, ending in .cpp
I used double.cpp
To compile from the command-line:
g++ -o double.cpp double
To run from the command-line:
./double
Here's the code:
#include <iostream> // Displaying simple text on screen
#include <cstdlib> // To use random() and srandom()
#include <unistd.h> // To use time() function
using namespace std; // Simple names for cout and endl
// ----------
int roll6Sided()
{
// This function simulates a 6-sided
// die being rolled.
// It gives back a whole number
// between 1 and 6
return ( random() % 6 ) + 1;
}
// ----------
int main()
{
// Seed the random number process
srandom( time(0) );
int attempt = 1;
int firstRoll, secondRoll;
do
{
firstRoll = roll6Sided();
secondRoll = roll6Sided();
cout << "Rolled " << firstRoll;
cout << " and " << secondRoll << endl;
if ( firstRoll == secondRoll )
{
cout << "We rolled a double!" << endl;
cout << "Number of attempts taken: ";
cout << attempt << endl;
}
else
attempt++; // Increase number of attempts counter
} while ( firstRoll != secondRoll );
// Report back to Linux that there were no known errors
return 0;
}
Find out more - buy the book on Amazon!