Public Group

#### Archived

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

# Randomize

This topic is 5810 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 use the Randomize function (Rand) in C++?

##### Share on other sites
Hehe this might be a little unclear, so I''ll explain:

Say you wanted to have a random number from 1 to 10.

First, you should seed the random number generator with something, preferably a time function, like timeGetTime(), or clock(), so it''s always different. Do this only once in the very beginning of your program.

Then, to get a random number, you would use the random function something like this:

rand()%10 would give you a random number from 1 to 10. (Or 0 to 9, I forget)

rand()%20 would give you ..... 1 to 20

if you want from other numbers than 0 or 1, you have to use math.

like if you want a number from 10 to 20, you should do something like

rand()%10 + 10;

get it? =D

-=Lohrno

##### Share on other sites
Never use modulus with rand. Use division instead, or you''ll screw up even distribution:

int random_number = float(rand())/RAND_MAX*max;
int random_number = lower_bound+float(rand())/RAND_MAX*(upper_bound-lower_bound);

##### Share on other sites

  #include <stdlib.h>#include <iostream.h>#include <time.h>void main(){	srand( (unsigned)time( NULL ) );    // generate your random seed	cout << "Random number between 0 and 9: " << rand()%10 << endl;	cout << "Random number between 0 and 19: " << rand()%20 << endl;	cout << "Random number between 0 and 99: " << rand()%100 << endl;	cout << "Random number between 0 and 5000: " << rand()%5001 << endl;}

EDIT: forget source brackets ;-)

[edited by - bangz on May 5, 2002 9:23:09 PM]

##### Share on other sites
Can we do something like this?
-----
armorE = rand() % armorEP;
-----

##### Share on other sites
quote:
Original post by IndirectX
Never use modulus with rand. Use division instead, or you''ll screw up even distribution:

How would this affect the distribution?

##### Share on other sites
How can you random, but then DONT get the same number again?

##### Share on other sites
If I wanted to get a random number in plain ansi c,
would I also have to create a ´seed´ first or use the time function? if do, how would I go about doing this?

PEACE

##### Share on other sites
Carrot : if RAND_MAX == 10 and you call rand() % 3 the probability would be : 0=4 1=3 2=3. In the long run this makes for a big mistake and since that mistake is alway in the low number it imbalance things.

You should use this formula to have balanced probability :
Result = int(rand() / (RAND_MAX + 1.0f) * Delta)

##### Share on other sites
If RAND_MAX was 10, random numbers would suck.

However on my machine it''s 32767, so what''s the problem?

• 40
• 12
• 10
• 10
• 9
• ### Forum Statistics

• Total Topics
631371
• Total Posts
2999611
×