[cs23021-2] Problem we discussed

Mikhail Nesterenko mikhail at cs.kent.edu
Wed Oct 7 09:48:09 EDT 2009


If you use random functions: rand() and srand() a (pseudo) random
number generator is incorporated in your program. The rule is that
before the generator can be used it has to be initialized. The
initialization is done with srand() function that takes an integer
called seed. The random number generator should be initialized only
once, so do not invoke srand() more than once in your program.  If
srand() is called with the same seed, for example if the program is
executed twice, then the successive calls to rand() are going to
return the same sequence.

Here is an example

///////////////
srand(2); // calling srand() with seed 2
int i1 = rand(); // rand() returns the first random number 23456
int i2 = rand(); // rand() returns the second random number 342156
int i3 = rand(); // rand() returns the third random number 897649
//////////////

Let us execute the same code with a different seed

///////////////
srand(3); // calling srand() with seed 3
int i1 = rand(); // rand() returns the first random number 7897897
int i2 = rand(); // rand() returns the second random number 4897874
int i3 = rand(); // rand() returns the third random number 89089076
//////////////

Now let us execute the same code but with the same seed as the first time

///////////////
srand(2); // calling srand() with seed 2
int i1 = rand(); // rand() returns the first random number 23456
int i2 = rand(); // rand() returns the second random number 342156
int i3 = rand(); // rand() returns the third random number 897649
//////////////


The point is that if the seed is the same, then the sequence of the
values returned by rand() is going to be the same.  The values inside
this sequence are still going to differ from each other.

Now, to prevent your programs from always giving the same results, you
are asked to initialize the random number generator with time(). This
way every time you run your program, the random number generator will
supply a different sequence of random values.

Thanks,
--
Mikhail


> Professor-

> But than how are number and number_2 different values if they
> operate off of the same seed? And if I were to somehow pause the for
> loops (include a cin>> that would wait for user input every time,
> but the input is never used) would the values change?


More information about the cs23021-2 mailing list