2

If I comment out the line with srand, the program will work, but there is no seed so the values will be the same each time. The assignment requires that I use rand, srand, and time to have the dice function be completely random.

#include <iostream>
#include <cstdlib>
#include <cmath>
#include <ctime>

using namespace std;

int rollDice();
// function declaration that simulates the rolling of dice

int main() {

    int roll1 = rollDice();

    int roll2 = rollDice();

    // define, initialize, and combine dice roll total

    int total;

    total = 0;

    total = roll1 + roll2;

    * this is where a bunch of stuff is output to the screen from the dice rolls, using total as well as some other stuff that is being calculated, i left it out for simplicity*

}

// function to simulate a random dice roll

int rollDice() {

    int r;

    srand (time(NULL));

    r = (rand() % 6) + 1;

    return r;

}
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
opticks
  • 59
  • 1
  • 1
  • 4

1 Answers1

6

Put srand in the main and call it once. You have to use the seed once to get all the results from a random sequence.

Here you restart the sequence every time you roll the dice.

See the documentation for srand()

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
dzada
  • 5,344
  • 5
  • 29
  • 37
  • THANKS! none of the answers I saw on google mentioned that the srand had to be initialized in the main program! – opticks Sep 10 '13 at 21:25
  • 5
    @user2766542: The main thing to understand is how pseudo-random number generation works. You seed the random number generator, and that gives you a reproducible sequence of numbers. So you seed it once, normally in `main()` but not necessarily. If you seed it every time, you will get poor results. `time()` has a granularity of one second. So if you ask for multiple random numbers within a second they may all have the same value! – Fred Larson Sep 10 '13 at 21:29