# C++ Beginner Question About Random Numbers



## rankbeginner (Jun 24, 2004)

Hello Experts and Thanks in Advance,

(Full disclosure: the following question is a very very small part of a class assignment. It is one step in a journey of 1,000 miles for a beginning programmer. But if you have objections to helping with assignments, then don't reply, or please suggest other sources to find an answer. )

In the following code, I am trying to generate a Random Number between 1 and 10. But each time I run this program, the number comes out to be "2". ... I want a random number each time. How can I fix this?

Please see code below ...

// Can the Tortoise beat the Hare?

#include <cstdlib> 
using namespace std;

int main()
{
int whereIsTortoise = 1;
int whereIsHare = 1;
int tortoiseMove;

cout << "The Classic Race Between the Tortoise and the Hare Begins !" << endl;
cout << "The first runner to reach Square Number 50 wins !" << endl;

cout << "The tortoise is now at square " << whereIsTortoise << endl;
cout << "The hare is now at square " << whereIsHare << endl;

tortoiseMove = 1 + rand() % 10;
cout << tortoiseMove << endl;

system("PAUSE"); // this hopefully will prevent the program from flashing by too fast to see!
return 0; // the classic way to end the program!

} // end of the function named main


----------



## Shadow2531 (Apr 30, 2001)

This should give you an idea.

http://forums.techguy.org/t261354.html


----------



## rankbeginner (Jun 24, 2004)

Thanks very much, Shadow2531. Yes, that did give me an idea, and a few more. ...

After getting the point from your post, I read some online tutorials about random number generation, and then I went back to my program code. I found that by entering these code lines, I could generate a random number (between 1 and 10) -- a different one each time:

srand (static_cast<unsigned>(time(0)));
for ( int counter = 0; counter < 1; counter++ ) {
randomNumber = 1 + (rand() %10) ;

It works: the only problem is that I do not fully understand what is happening in the line

srand (static_cast<unsigned>(time(0)));

Any clues would be appreciated!

--RB


----------



## Shadow2531 (Apr 30, 2001)

static_cast<unsigned>(time(0)) just converts time(0) to an unsigned int type since it's not going to be negative. However it's probably not super necessary that you use static_cast in this instance.

Just like static_cast<char>(94) converts 94 to it's char representation, which is ^.

Anyway, the problem with using the time to seed the random number generation is that annother operation could happen before the time changes and you'll get the same value.


----------



## Shadow2531 (Apr 30, 2001)

try this


```
#include <iostream>
#include <ctime>
#include <cstdlib>

using namespace std;

int main() {
    for ( int i = 0; i < 10; i++ ) {
       srand(time(0));
       cout << 1 + (rand() %10) << endl;
    }
}
```
then try this


```
#include <iostream>
#include <ctime>
#include <cstdlib>

using namespace std;

int main() {
    for ( int i = 0; i < 10; i++ ) {
       srand(time(0) + i);
       cout << 1 + (rand() %10) << endl;
    }
}
```
The time alone doesn't change quick enough, which is why you add something else in the mix.

This bottom example will still output the same random numbers if you run the program twice in under a second.


----------



## jamesh2923 (Aug 22, 2004)

rankbeginner,

It is not necessary to re-initialize the rand() function each time a number is needed. 

Initialize using the srand() function out side of your for loop. This is just good programing practice.

Here is a code fragment...

srand( (unsigned)time(null));
for(i=0; i<10; i++)
printf(" %6d\n", rand());

This will generate 10 random numbers.


----------



## rankbeginner (Jun 24, 2004)

Thanks Shadow and jamesh ... I will try these suggestions and then report back if I still need clarification. Best wishes ... RB


----------



## Shadow2531 (Apr 30, 2001)

jamesh2923 said:


> It is not necessary to re-initialize the rand() function each time a number is needed.


That is true if you are just going to be printing 10 random numbers and be done with it. However if you are doing something more, using the same seed value throughout will cause the program to output the same set of random numbers.

Any of the above examples in this thread will output the same set of random numbers if you run the program twice in under a second. That, you don't have to worry about too much, but if a function is called twice in under a second it can output the same set of random numbers. My point is only to be careful, but you'll definitely know it if get the same set of random numbers.

That's why some programs will wait for 1 second to make sure the seed value changes before generating another random number. If time() was based on something smaller than a second, you wouldn't have to worry as much.

Here's an example that will wait for a second when the program starts. You can use the same type of method before calling a function each time too, if you need to be sure it doesn't output the same set of random numbers.


```
#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main() {
    int x = time(NULL);
    int dummy = 0;
    while (x == time(NULL)) {
        dummy += 1;
    }
    srand(time(NULL));
    for (int i = 0; i < 10; i++ ) {
        cout << 1 + rand() % 10 << endl;
    }
}
```


----------

