Archived

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

sir hackalot

random numbers

Recommended Posts

well, for a random number, you include, um... (i hope this is the right header) and then you do this:

int rand_num = rand()%6;

and rand_num should contain a number between 1 and 6. it''s not COMPLETELY random, though. to make it more random, you should put:

srand(timeGetTime());

before you use rand(). you don''t have to use timeGetTime(), its just good because its always changing. srand() will seed the random number to make it more random.

for the second question, you could do this:

int rand_num = rand()%6;
int rand_num2 = rand()%6;
while(rand_num2 == rand_num)
{
rand_num2 = rand()%6;
}

hope that helps


_________________Gecko___
Gecko Design

Share this post


Link to post
Share on other sites
quote:
Original post by sir hackalot

How do you generate a random number between 0 and 5 in C?

Is there also a way I could make sure the same number is not
chosen?


Although it makes little difference when you only have 6 numbers, if you ever need to do the same thing for 100, or 1000 numbers, rather than the above method of keeping generating the random numbers until you finally get one that isn''t already taken, you should consider generating an array of all the possible numbers in order, and shuffling them. One ways is to just loop through the array, swapping the given element with a randomly chosen other element. This gives a pretty random distribution.

Share this post


Link to post
Share on other sites