Program doesn't work
May 5, 2012 at 4:16am UTC
Hey, I am trying to make a program which simulates a game which works like this:
The object of the game is to reach 21 points first without going over. When both players reach 21 on the same number of rolls, or if both players “bust” on the same number of rolls, a tie occurs. If only one player "busts" in a roll, that player loses.
When I run the program (on compilr.com), I get this error after I input how many games I want to play:
bash: line 1: 278 Segmentation fault ./program
Here's the code for my program
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 50 51
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <iomanip>
#include <iostream>
using namespace std;
void playGame();
int main()
{
int games;
int gNumber;
cout << "How many games do you want to play? " ;
cin >> games;
for (gNumber = 1; gNumber <= games; gNumber++)
{
cout << "\n *** GAME " << gNumber << "*** " ;
cout << "\nRoll Player 1 Player 2" ;
playGame();
}
}
void playGame()
{
int points[2][21];
int p1 = 0, p2 = 0;
int i = 1;
srand ( time(NULL) );
do
{
cout << "\n " << i;
points[1][i] = p1 + rand() % 6 + 1;
points[2][i] = p2 + rand() % 6 + 1;
p1 = points[1][i];
p2 = points[2][i];
cout << setw(8) << points[1][i] << setw(8) << points[2][i];
i++;
}
while (points[1][i] < 21 || points[2][i] < 21);
}
Thanks!
May 5, 2012 at 6:12am UTC
Although you didn't really ask a question, try this:
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
#include <stdlib.h>
#include <time.h>
#include <iomanip>
#include <iostream>
using namespace std;
void playGame();
int main()
{
int games;
srand ( time(NULL) );
cout << "How many games do you want to play? " ;
cin >> games;
for ( int gNumber = 1; gNumber <= games; gNumber++)
{
cout << "\n *** GAME " << gNumber << "*** " ;
cout << "\nRoll Player 1 Player 2" ;
playGame();
}
}
void playGame()
{
int p1 = 0, p2 = 0;
int i = 1;
do
{
p1 += rand() % 6 + 1;
p2 += rand() % 6 + 1;
cout << "\n " << i++;
cout << setw(8) << p1 << setw(8) << p2;
}
while ( p1 < 21 and p2 < 21 );
}
May 5, 2012 at 1:46pm UTC
It works! Thanks! But Im wondering, what was wrong with my program before?
Topic archived. No new replies allowed.