-3

My code deals with two dice (a 10 sided "fair" dice and a 20 sided "fair" dice) and using classes, arrays and a random number generator to generate random rolls of the two dice and their summation, but all my code spits out is "You rolled: 18". That is not very random.


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

using namespace std;

class Dice
{
  private:
  int rollDice[2] = {};

  public:
  void setval1(int x)
  {
    rollDice[0] = x;
  }

  void setval2(int y)
  {
    rollDice[1] = y;
  }

  double getVal1()
    {
      return rollDice[0];
    }

  double getVal2()
  {
    return rollDice[1];
  }
};

int main()
 {
  Dice a;
  a.setval1(rand()%9+1);
  a.setval2(rand()%19+1);
  cout << "You rolled: " << a.getVal1() + a.getVal2();
}

1 Answers1

0

From the documentation :

You need to seed the pseudo-random number generator used by std::rand(). If rand() is used before any calls to srand(), rand() behaves as if it was seeded with srand(1).

Each time rand() is seeded with the same seed, it must produce the same sequence of values.

Correct usage in C++ would be something like this :

std::srand(std::time(nullptr)); // use current time as seed for random generator
int random_variable = std::rand();

If you want a specific statistical distribution you should look at the header random documentation

Clonk
  • 2,025
  • 1
  • 11
  • 26
  • How would that be implemented in my code though? Also, i am confused by what you mean by your comment "use current time as seed for random generator". – AstroNOT98 Apr 01 '19 at 11:47
  • I apologize. I am still relatively new to C++. @Clonk – AstroNOT98 Apr 01 '19 at 11:49
  • True randomness does not exists in computer. Therefore, computer use [pseudo-random](https://en.wikipedia.org/wiki/Pseudorandom_number_generator). For a given distribution and seed, the sequence of "random" numbers will always be the same. If you reinitialize the generator with the same seed, you will obtain the same number. The system time / ticks of your CPU is a good way to obtain integers that will be different each run. So unless you need to generate random number for cryptography purpose, it's generally good enough to use as a seed to obtain a different sequences each run. – Clonk Apr 01 '19 at 11:55
  • 1
    @AstroNOT98 Also remember to seed only 1 time at the beginning of `main()`. Don't try to seed each time you need a new random number. Some users do the latter and then ask why the numbers are not random. If you seeded in a loop remember that the resolution of the clock is 1 second so it will give the same seed inside of a second. same seed means same random number. This is why its best to just seed at the 1 time at the beginning of main(). – drescherjm Apr 01 '19 at 13:18