-2

I am pretty new to C++ and am trying to make a simple die roll with a Die class/main.

I can get a random number within my range 1-dieSize, however, each time I "roll the dice" it just gives me the same random number. For example, when I roll this dice three times, it will cout 111 or 222 etc instead of 3 different random rolls. Any help explaining this issue would be much appreciated!

My die header is just a basic header. My issue I'm assuming is with the random function.

main:

int main()
{
// Call menu to start the program
Die myDie(4);

cout << myDie.rollDie();
cout << myDie.rollDie(); // roll dice again
cout << myDie.rollDie(); // roll again


return 0;
}

die.cpp:

Die::Die(int N)
{
//set dieSize to the value of int N
this->dieSize = N;
}

int Die::rollDie()
{
    // Declaration of variables
int roll;
int min = 1; // the min number a die can roll is 1
int max = this->dieSize; // the max value is the die size

unsigned seed;
seed = time(0);
srand(seed);

roll = rand() % (max - min + 1) + min;

return roll;
}

In die.cpp I have the cstdlib and ctime included.

melpomene
  • 84,125
  • 8
  • 85
  • 148
Ali
  • 9
  • 1
  • 2
  • 3
  • 4
    Don't call `srand` more than once. – melpomene Jul 16 '17 at 22:11
  • As you ever use srand with time(0) right before rand you will get the same numbers inside the same second. So you should not call srand every time or use time(0) and the last random or use a time function with higher resolution, – Tobias Wollgam Jul 16 '17 at 22:15
  • Here's another duplicate: https://stackoverflow.com/questions/1108780/why-do-i-always-get-the-same-sequence-of-random-numbers-with-rand – user0042 Jul 16 '17 at 22:32
  • best way: https://xkcd.com/221/ – sp2danny Apr 10 '19 at 12:57

1 Answers1

0

As melpomene suggested in the comment you should initialize the seed of the random only once at some point of the program.

The rand() function is not really a random number creator, rather a sequence of bit manipulation on the previously generated value, which starts with the first value that is generated by the seed (calling srand(seed)).

#include <iostream>
#include <cstdlib>

int rollDie()
{
    int roll;
    int min = 1; // the min number a die can roll is 1
    int max = 6;// this->dieSize; // the max value is the die size

    roll = rand() % (max - min + 1) + min;

    return roll;
}

int main()
{
    srand(time(0));
    for(int i=0;i<10;i++)
    {
        std::cout << rollDie() << std::endl;
    }
}

There is a good chance that you are already using C++11, so you should read and practice with the random library: http://en.cppreference.com/w/cpp/numeric/random

Community
  • 1
  • 1
ZivS
  • 2,094
  • 2
  • 27
  • 48