Jump to content
  • Advertisement

Archived

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

WhoStoleMyNick

How do I generate a random number in C++ with a set range?

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

Guest Anonymous Poster
Well you would first want to include
srand(time(NULL));
to seed you number in you initialization and then whenever you want a new number you would call
int newrandomnum = rand() % num;
This will produce a number from 0 to num - 1.
You have to #include <time.h> for time and I think stdlib.h for the rand() though I'm not to sure.
Big Daddy Scat

Share this post


Link to post
Share on other sites
Advertisement
Guest Anonymous Poster
2+2=4

Share this post


Link to post
Share on other sites
If you want to generate a random integer between 1 and 10, you should always do it by

j=1+(int) (10.0*rand()/(RAND_MAX+1.0));


the rand()%x function only uses lower-order bits and will generate a much LESS random number( Numbers are never completely random in computers ) then the first method.

Yeah it seems much more complex, but just through it in a function.

On the otherhand if you don't really care how random the numbers really are and thats not important to you, the simpler way will work.

------------------
Gary
Midnights Dawning Software
http://dawning.dhs.org


Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Darvith is right, and most good manuals will suggest the floating point random number method.

The following macro will return a random number between min(inclusive) and max(exclusive):


#define randomRange(min, max) ( (int)(min + (max-min)*rand()/(RAND_MAX+1.0)) )

randomRange(1, 10) will then return a random integer between 1 and 10.
You will also need to #include and call srand(time(NULL)); as mentioned by others. #include is not strictly necessary, since you are not using the time_t structure in the call to time().

Regards,

White Fire

Share this post


Link to post
Share on other sites
Hello, I'm making a program in C++ that has to generate a random number within a set range. (the bottom number could be higher than 0) How do I do it?

------------------
|
|/
|\evin Clancy

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
That is, you will need to #include stdlib.h, but time.h is not strictly necessary.

White Fire

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!