C++ rand generates the same number with srand time

Random number generation in C++ in the standard libraries is generally done using “ctime” (time.h) and “cstdlib” (stdlib.h). If you are experiencing an issue where calling rand() keeps generating the same number due to similar seeds, simply call it multiple times. (See below).

int main() {

//repeat as many times as you like to prove randomness
cout << GetRandomNumber(10) << "\n\r";
cout << GetRandomNumber(10) << "\n\r";
cout << GetRandomNumber(10) << "\n\r";
cout << GetRandomNumber(10) << "\n\r";
cout << GetRandomNumber(10) << "\n\r";

int pause;
cin >> pause;
return 0;
}

int GetRandomNumber(int upperlimit) {
    srand(time(NULL)); //use time which is accurate within seconds to generate random seed

rand();rand();rand(); //call rand multiple times to create more variance since subsequent calls within a short time frame will have a similar result

return rand() % upperlimit; //passing in 10 will generate from 0-10, 100 generates 0-100 etc.

}

References
Stackoverflow (blog), http://stackoverflow.com/questions/3032726/rand-generating-the-same-number-even-with-srandtimenull-in-my-main
LearnCPP, http://www.cplusplus.com/reference/clibrary/cstdlib/rand/

Advertisements

About Ronnie Diaz

Ronnie Diaz is an enterprise software engineer responsible for front-end and back-end development for companies in many industries. Heavily involved in cloud development, online retail, e-commerce and electronic ordering, fulfillment and customer relational systems.

Posted on June 3, 2011, in Programming & Development and tagged , , , , , , , , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: