Advertisement

random numbers

Started by April 09, 2000 09:58 PM
2 comments, last by sir hackalot 24 years, 7 months ago
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? An example would be nice, thanks alot!!!!!!!!
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

_________________Gecko___Gecko Design
Advertisement
sorry, rand_num will contain a number between 0 and 5, not 1 and 6.


_________________Gecko___
Gecko Design

_________________Gecko___Gecko Design
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.

This topic is closed to new replies.

Advertisement