Generating 2 different random numbers

I'm back with more problems. this time around I need some help with get this program to generate to diffrent random numbers from 1-14. I have tries a few diffrent thing and I can only get it disply the same number twice, but I need it display 2 different numbers. Well, if anybody can help me with this it would be very great, thanks alot. Here is my code.

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

using namespace std;

int main()
{
for (int i =0; i < 1; i++)
{

srand ( time(NULL) );

int card1 = (rand() % 14 +1);

cout<<card1;
cout<<endl;
}


for (int i =0; i < 1; i++)
{

srand ( time(NULL) );

int card2 = (rand() % 14 +1);


cout<<card2;
cout<<endl;
}
system("pause");

return 0;
}
Only call srand() once. In your program call it as soon as main starts, and don't call it again. You should get different numbers after that.
I know not to call it more than once, but why?
A pseudo random number generator is just a math equation.

Basically how it works is it takes an input number X and produces output number Y. Y is both your random number, and the next input number X.

The "seed" is the first value for X, which gets everything started. This is what srand does. It basically restarts the PRNG at a new starting point. Seeding with the time is a common way to make it so that the RNG starts with a unique input value X every time, which makes the numbers appear random.

Not only is reseeding with the time over and over completely unnecessary, but it might also produce more predictable numbers than letting the RNG run without seeding. After all the time just increments steadily, but the output value Y will be very different every time.

Seeding multiple times can be useful if you want to "remember" or recreate a sequence of random numbers. If, for example, you made a game where the maps are randomly generated, but you wanted to remember how to recreate the map over and over again. You could just record the seed used for the map rather than recording the entire map, that way you'd be able to just reseed with that seed and produce the exact same map every time.

EDIT:

In your case here, srand() in a loop is a very bad idea because it's likely that time() returns the same value every iteration (the computer moves so fast that no milliseconds or whatever have passed between time() calls). Which means the RNG is seeded with the same number every time, which means rand gives you the same number every time.
Last edited on
Topic archived. No new replies allowed.