#### Archived

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

# random numbers

This topic is 6770 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

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!!!!!!!!

##### Share on other sites
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 on other sites
sorry, rand_num will contain a number between 0 and 5, not 1 and 6.

_________________Gecko___
Gecko Design

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

1. 1
Rutin
47
2. 2
3. 3
4. 4
5. 5

• 13
• 10
• 12
• 10
• 13
• ### Forum Statistics

• Total Topics
632992
• Total Posts
3009755
• ### Who's Online (See full list)

There are no registered users currently online

×

## Important Information

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!