//First Example
//This program counts how many times
//it takes until a die rolls with the
number
//that the user input
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace
std;
int rollDie(int);
int main()
{
srand(time(0)); //seed the random
number generator
int
times,number;
cout << "Which number do you want (1-6)?";
cin >> number;
times = rollDie(number);
cout << "It took " << times << " rolls to
"
<<
"get "
<< number;
}
int rollDie(int x)
{
//roll the die until it hits the number x
int
roll;
int
counter = 0;
while (true)
{
roll = rand() % 6 + 1; // a random
number between 1 and 6
cout << "You rolled: " << roll << endl;
counter++;
if (roll == x)
return counter;
}
}
//Example 2
//User inputs the sum of the two dice
//this program simulates the rolling
of two dice
//counting how many times it takes
until the sum
//is equal to the user input
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace
std;
int rollDie(int);
int main()
{
srand(time(0));
int
times,sum;
cout << "Which sum do you want (2-12)?";
cin >> sum;
times = rollDie(sum);
cout << "It took " << times << " rolls to
"
<<
"get "
<< sum;
}
int rollDie(int x)
{
int
die1,die2;
int
counter = 0;
if (x < 2 || x >
12) //checking
to see if the sum value is impossible!
{
cout << "ERROR IN SUM!";
return 0;
}
while (true)
{
die1
= rand() % 6 + 1; //two
random numbers between 1 and 6
die2
= rand() % 6 + 1;
cout << "You rolled: " << die1 << " and "
<<
die2 << endl;
counter++;
if (die1 + die2 == x)
return counter;
}
}