1

I cannot seem to get the rand() function to work properly. Here is a sample of my code that asks for the number of sides of the die and then should generate a random number(a roll of the die) based on the number of sides. I keep getting the same number in the value variable. What am I doing wrong?

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


using namespace std;

int main()
{

    int numSides;
    int value;
    cout << "Please enter the number of sides of the dice: ";
    cin >> numSides;

    value = rand() % numSides + 1;

    cout << endl << value;


}
  • 4
    You need to seed the RNG, otherwise you get the same random sequence every time you run the program. – Barmar Sep 23 '20 at 22:43
  • 2
    ***I keep getting the same number in the value variable*** That is because you forgot to seed the random number generator 1 time at the beginning of your main(). – drescherjm Sep 23 '20 at 22:43
  • 1
    You are not initializing the random number generator with a random 'start' value, so it will always produce the same sequence of numbers. Add #include and at same stage before the call to rand, add the following code srand(time(NULL)); – CraigR Sep 23 '20 at 22:45
  • 2
    Check out [`rand()` Considered Harmful](https://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful). – Mark Ransom Sep 23 '20 at 22:49

0 Answers0