Issues with rand and srand

65 views Asked by At

I'm making a program to get the average number of dice rolls to get a 6, but there seems to be an issue with the RNG. I suspect it's the seed, as while the number is different each time I compile and run the code, it doesn't change in each individual attempt, so the average doesn't change. Heres my code:

#include <iostream>
#include <cstdlib>    // random numbers header file//
#include <ctime>    // used to get date and time information
using namespace std;

int main()
{
    int roll = 0;       //declare a variable to keep store the random number
    int i = 0;
    int counter = 0;
    int resume = 1;
    int average = 0;
    int totalrolls = 0;

    srand(time(0)); //initialise random num generator using time

    while (resume != 0) {
        while (roll != 6) {
            roll = rand() % 6 + 1; // generate a random number between 1 and 6
            i++;
        }
        counter++;
        totalrolls += i;
        average = totalrolls / counter;
        cout << "the average number of rolls to get a 6 is " << average << ", based on " << counter << " sixes." << endl;
        cout << "do you wish to keep rolling? ";
        cin >> resume;
        cout << endl;
    }

return 0;
}

Anyone got any idea what's going on?

1

There are 1 answers

0
templatetypedef On BEST ANSWER

Notice that roll only gets updated inside this loop:

while (roll != 6) {
   ...
}

This means that after that loop finishes running with roll set to 6, it will never run again, even if the outer loop executes another time.

To fix this, you could either

  1. change this to be a do ... while loop so that it always executes at least once; or
  2. manually reset roll to a value other than 6 on each iteration through the outer while loop; or
  3. change where roll is defined so that it's local to the outer while loop and so you get a fresh copy of it per outer loop iteration, which is basically a better version of option (2).