Jump to content
  • Advertisement

Archived

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

Mister Stewart

rand() problem

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

Okay, suppose I had a bunch of values: #define ATTACK 0 #define MOVE_UP 1 #define MOVE_DOWN 2 #define MOVE_LEFT 3 #define MOVE_RIGHT 4 then I had something like this: #define NO_OF_MOVES 4 now, lets say I wanted to select one of those five values at random, I would do this: rand()%NO_OF_MOVES Here''s the problem - as it is this code seems to only select all but MOVE_RIGHT, so I changed the code to this: rand()%(NO_OF_MOVES+1) that didn''t work for some reason. Is this how rand()works? It selects a random number except the one specified? Any suggestions as to how I can do this, so all the values can be chosen from. Thanks. I do not have to destroy, because I do not fear.

Share this post


Link to post
Share on other sites
Advertisement
Actually what you want to do is rand()%5. Becuase there are 5 moves ( 0, 1, 2, 3, 4 ). doing rand()%5 will look at 0-4. doing (rand()%4)+1 will only look at 1-4. Hope this helps

Share this post


Link to post
Share on other sites
If you want to have different value each time your random is executed, you have to set your random.

Use "srand (NULL)"...

Don''t remember the syntax though.

Share this post


Link to post
Share on other sites
srand(NULL) probably wouldn''t work. You''re seeding the random number generator with a NULL all the time, which isn''t very random. What you should do is to see the generator with the time, which would be more random.

srand(time(NULL));

That''ll work better

Share this post


Link to post
Share on other sites
quote:
Original post by Chronoslade

Rand() is offset by one as in the way array''s are.

"There is humor in everything depending on which prespective you look from."


rand() isn''t offset by one. It is a function that returns a value between zero and RAND_MAX. Usually, you then use the modulus operator (%) to get a value between zero and the number you are ''modding'' by. A modulus is essentially the remainder of the division for that number. For example, 9%2 would be the remainder from 9 divided by two (which equals 1).

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!