Pregunta

I've been working on practice problems for my Computer Science class, and one of them reads the following:

A pair of dice is rolled repeatedly. If "box cars" (6-6) shows up, player A wins. If not, but 7 shows up twice in a row (as in, one die shows 7 and then after you roll both die again, another 7 shows up), B wins. Write a C++ program to roll a pair of dice 1000 times and output how many times A and B would have won.

So I've gotten the main backbone to the program and have tested it a few times, but every single time so far the B player shows up as winning 0 times. The A player's wins have fluctuated each time I've run the program, so I believe that A is correctly coded but any tips or debugging will be greatly appreciated. The program:

#include <iostream>
#include <ctime>
using namespace std;

int main()
{
int die1, die2, store = 0, awin = 0, bwin = 0;

srand(time(NULL));

for(int i = 0; i < 1000; i++)
{
    die1 = rand()% 6+1;
    die2 = rand()% 6+1;

    if(die1 == 6 && die2 == 6)
    {
        awin++;
    }
    else if(die1 == 7 || die2 == 7)
    {
        store = 1;
    }

    if(store == 1 && die1 == 7)
    {
        bwin++;
        store = 0;
    }
    else if(store == 1 && die2 == 7)
    {
        bwin++;
        store = 0;
    }

    store = 0;
}

cout << "A has won " << awin << " times and B has won " << bwin << " times." << endl;

system("pause");

}

¿Fue útil?

Solución

rand() % 7 will NEVER give you a result of 7. It's the remainder of a number divided by 7, so you'll get anything between 0 and 6.

With your comment in mind, just check that die1 + die2 == 7 and you'll be sorted.

Otros consejos

rand()%6+1 returns a range from 1-6.
store is only ever being assigned on the condition that a die rolls 7, which never happens.
bwin is only ever being incremented if store is equal to a die roll, which also never happens, since store is initialized to 0 and the conditions to re-assign it (rolling 7) can never be met.
Therefore, bwin is always 0 and awin increments only when both dice roll 6.

Everything through this part seems correct:

if(die1 == 6 && die2 == 6) {
    awin++;
}

It's after this that things get sideways.

First, check to see if the previous roll was 7 and if the current roll matches the previous roll:

if(store == 7 && store == die1 + die2) {

If that evaluates to true, b has won:

    bwin++;
}

Then store the value of the current roll so you'll know about it on the next roll:

store = die1+die2;

You shouldn't be checking each die against 7 but rather the sum of the two dice.

Try this

for(int i = 0; i < 1000; i++)
{
    die1 = rand()% 6+1;
    die2 = rand()% 6+1;

    if(die1 == 6 && die2 == 6)
    {
        awin++;
    }
    else if (store == 7 && (die1 + die2) == 7)
    {
        bwin++;
    }

    store = die1 + die2;
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top