Jump to content
  • Advertisement


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


Questions about srand.

This topic is 5829 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 i was browsing gametutorials.com and downloaded their tutorial onhow to call random numbers. I was looking because i had some code for a blackjack game that i was trying to understand. The tutorial described several ways to get a random number and explained them all except for one. In the last bit of the tutorial it said "There is another way to get a random number but get tick count is better" the code was #include <iostream> #include <time.h> using namespace std; int main() { srand(time(NULL)); int x = rand()%255; cout << x; return 0; } This is exactly how the blackjack code that i have does it, but the tutorial didnt mention how this works. What does (time(NULL)) mean? I know it generates random numbers but how? Thanks to anyone who can help me. "Poor is the pupil that does not surpass the master"

Share this post

Link to post
Share on other sites
The srand function sets the random seed to the argument that''s passed in. The time(NULL) function returns the system time, in seconds since January 1st, 1970. Currently that''s a number somewhere around 900 million.

Once the random seed is set, the rand() function will return a sequence of "pseudo-random" numbers every time it''s called. They''re not true random numbers; the sequence will repeat after
a certain (very large) number of calls.

The sequence of pseudo-random numbers returned will be completely different for each different seed that''s set with srand. That''s why the time(NULL) function is frequently used for this.

The line that does:
int x = rand()%255; 

This gets a random number, and returns the remainder of that number divided by 255. In other words, you get a number between 0 and 254 inclusive.

Hope this helps,

Cheers, dorix

Share this post

Link to post
Share on other sites
WOW thanks for the fast reply, i hated to ask a simple question like that but my C++ book doesnt even cover the rand function >

Then i found that tutorial and that was the only way to get a random number that it didnt explain?

"Poor is the pupil that does not surpass the master"

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.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!