#### Archived

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

# 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.

## 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.

it shouldn''t be
rand()%(4+1);
it should be
(rand()%4)+1;

##### Share on other sites
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 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 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 on other sites
Rand() is offset by one as in the way array''s are.

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

##### Share on other sites
quote:

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).

1. 1
2. 2
3. 3
frob
12
4. 4
5. 5
Rutin
10

• 13
• 14
• 65
• 14
• 15
• ### Forum Statistics

• Total Topics
632130
• Total Posts
3004284

×