rand() problem

Started by
5 comments, last by Mister Stewart 23 years ago
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.
"16 days?? that's almost two weeks!!" Tucker
Advertisement
it shouldn''t be
rand()%(4+1);
it should be
(rand()%4)+1;

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~I'm looking for work
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

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.
X-Fe@R... is back!------------------
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
==========================================In a team, you either lead, follow or GET OUT OF THE WAY.
Rand() is offset by one as in the way array''s are.

"There is humor in everything depending on which prespective you look from."
"There is humor in everything depending on which prespective you look from."
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).

This topic is closed to new replies.

Advertisement