Jump to content
  • Advertisement


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


Generating different sets of random numbers

This topic is 5643 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!