Jump to content
  • Advertisement

Archived

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

nickwinters

Generating Random Integers

This topic is 5593 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

Advertisement
quote:
Original post by nickwinters
Anyone know a Visual C++ 6.0 Library that generates random integers or floats?

-Nick


int Rand = rand () % 10

this will random numbers between 0 and 9

Share this post


Link to post
Share on other sites

      
#include <cstdlib>
#include <ctime>

// ...


srand( unsigned (time(NULL)) );
int rNumber = rand() % 100;


You must include cstdlib to use the rand() function, yet the rand() function will return the same random numbers every time your program runs, as it uses the result of the last call to rand() to seed the next call. If you seed it with a value before its first use, then the random numbers it produces wont all be the same. You need to seed it with something that changes, though, else they will be the same every time you run your program. Something that is always changing is time, so you can seed it with time.

To seed rand(), you invoke the srand() function (cstdlib), which takes an argument of type unsigned int as the seed value. If you include ctime you can use the time() function. You can merely call it with NULL.

The rand() function returns a value between 0 and a compiler dependant number (defined as MAX_VALUE or something, but you don't need to worry about it). So you can do:
rand() % 100
to get a number between 0 and 100.

:::: Lektrix ::::
[ Google || ACCU || BarrysWorld || E-Mail Me ]

[edited by - Lektrix on February 2, 2003 10:25:34 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.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!