jeudi 8 octobre 2020

Issues with rand and srand

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?




Aucun commentaire:

Enregistrer un commentaire