I have written this code and it works. However, I hope someone can give me some comments to improve it. Thanks in advance.
This is the question.
/*In the game of craps, a “Pass Line” bet proceeds as follows. The first roll of the two, six-sided dice in a craps round is called the “come out roll.” The bet immediately wins when the come out roll is 7 or 11, and loses when the come out roll is 2, 3, or 12. If 4, 5, 6, 8, 9, or 10 is rolled on the come out roll, that number becomes “the point.” The player keeps rolling the dice until either 7 or the point is rolled. If the point is rolled first, then the player wins the bet. If the player rolls a 7 first, then the player loses.
Write a program that plays craps using those rules so that it simulates a game without human input. Instead of asking for a wager, the program should calculate whether the player would win or lose. Create a function that simulates rolling the two dice and returns the sum. Add a loop so that the program plays 10,000 games. Add counters that count how many times the player wins, and how many times the player loses. At the end of the 10,000 games, compute the probability of winning, as Wins / (Wins + Losses), and output this value. Over the long run, who is going to win more games of craps, you or the house?*/
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
|
#include <iostream>
#include <cstdlib>
using namespace std;
int sdie ();
void setRandomSeed();
int main()
{
int i,wins=0, losses=0,roll1, roll2,thepoint;
setRandomSeed();
for (i=0;i<10000;i++)
{
roll1=sdie();
if (roll1==(7||11))
wins +=1;
else if (roll1==(2||3||12))
losses +=1;
else
{
thepoint=roll1;
do
{roll2=sdie();
if (roll2==thepoint)
{wins +=1;
break;}
else if (roll2==7)
{losses +=1;
break;}
}
while (roll2!=(thepoint&&7));
}
}
cout <<"Number of winnings is "<<wins << "."<<endl;
cout <<"Number of losings is "<<losses << "."<<endl;
cout <<"Prob. of winning is " << static_cast<double> (wins)/10000<<endl; //wins is integer so static_cast<double> changes it to double type.
return 0;}
void setRandomSeed()
{
int randSeed;
cout << "Enter a seed.";
cin >> randSeed;
srand(randSeed);
}
int sdie()
{
return (rand() % 6) + (rand() % 6) + 2;
}
|