Archived

This topic is now archived and is closed to further replies.

liquidAir

Generating different sets of random numbers

Recommended Posts

OK, here''s my problem. I use the rand() function to generate random numbers. Everytime I start the application, I always get the same set of numbers. How can I generate different sets of random numbers when I close and restart the application?

Share this post


Link to post
Share on other sites
You need to seed rand(). To do this you use the srand() function, also defined in cstdlib. You must seed it with a different number each time, and one way of doing this is to seed it with the time. You can use the time() function, defined in ctime, and just pass null to it, to get the time. srand() takes an unsigned int argument, and time() returns a time_t, which is generally defined as a long, so I have type casted the return value to an unsigned int. The compiler will, though, do this for you implicitely.

#include <iostream>
#include <cstdlib> // for rand() (and srand())

#include <ctime> // for time()


int main()
{
srand( unsigned ( time(0) ) ); // seed random number


std::cout << rand() % 10 + 1 << std::endl;
// ... etc


return 0;
}

Edit: Have a look on Google for information on what seeding rand() is and why you have to do it.

[ Google || Start Here || ACCU || STL || Boost || MSDN || GotW || MSVC++ Library Fixes || BarrysWorld || E-Mail Me ]

[edited by - Lektrix on July 5, 2003 11:10:12 AM]

Share this post


Link to post
Share on other sites