user2877477
user2877477

Reputation: 263

C++ Dice Program Difficulties

Question:

Repeatedly roll 3 dice until doubles are rolled (any two are the same). Show the values each time and afterwards state how many tries it took to get doubles.

My code:

#include <iostream>
#include <time.h>
#include <stdlib.h>
#include <string.h>

using namespace std;

int main ()
{
    srand (time(NULL));
    int j=1;
    int i=0;
    int a;
    int b;

    do
    {
        int a=(rand ()%6+1);
        int b=(rand ()%6+1);

        cout<<a<<" and "<<b<<endl<<endl;
        j++;
    }
    while (a!=b);

    cout<<"They are the same!"<<endl<<endl;
    cout<<"It took "<<j<<" tries.";

    return 0;
}

Problem:

The loop doesn't stop. Even when a and b are the same the program doesn't stop.

Upvotes: 1

Views: 627

Answers (2)

Charlie
Charlie

Reputation: 1582

You're declaring new variables inside the loop that shadow the a and b that you declared outside of the loop. while (a != b) is looking at the outside ones, but you're not changing those.

Get rid of the int on int a = (rand() % 6) + 1

If you're using gcc/g++, you could probably save yourself some pain with the -Wshadow flag to your compiler. For other compilers, I don't know what the option is, but there probably is one. At least that'd tell you the problem at compile time instead of run time.

Upvotes: 1

jlahd
jlahd

Reputation: 6293

You are redefining a and b inside your do ... while loop. Remove the int before the second a and b definitions, where you assign the random values to the variables, and it will work.

Upvotes: 6

Related Questions