# Random Function

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

## Recommended Posts

What's the random function? Also, how should i make my own random function that takes in a Min, and Max and returns a value between the two?

##### Share on other sites
Programming language?

sry, C++

?

##### Share on other sites
The C standard random function is rand. On operating systems that support them, you should use random or rand48 instead. Generating random numbers within bounds is as easy as n = min + rand() % (max-min).

##### Share on other sites
Quote:
 Also, how should i make my own random function that takes in a Min, and Max and returns a value between the two?

int randomNumber = (rand() % (max-min)) + min;

##### Share on other sites
doesn't rand() return a value between 0 and 1? (if not using srand(long) to define that max)

Here's what i came up with, is thie correct?

long GenerateRandom(long Min, long Max)
{
long Num;
srand(Max - Min);

Num = rand() + Min;
return Num;
}

##### Share on other sites
srand sets the seed for the random number generator. The seed should be from a constantly changing source. A milli or microsecond counter would work. As stated in the manpage, rand returns an integer between 0 and RAND_MAX as defined in stdlib.h. Read the linked manpage for details.

Sidenote: Variable names begin with lowercase letters by convention.

##### Share on other sites
what about a random floating number between two floats? how would i figure that out?

##### Share on other sites
step-by-step how to do it:
float RN = rand();float result1 = RN / RAND_MAX;float low = 2, high = 5;float result1 = result1 * (high - low) + low;cout << "result: " << result2 << endl;

one line way to do it(assuming high and low are defined floats:
float result = (rand()*1.0 / RAND_MAX) * (high - low) + low;

It is VERY important that rand() be converted into a floating point number in C++. If you have an integer divided by another integer it rounds so if you have, say rand() equals 10 then 10 / RAND_MAX will be zero. If you convert it to a float before hand then it will do floating point math and you won't lose any precision. The code is fairly straight forward, I hope.

• ### What is your GameDev Story?

In 2019 we are celebrating 20 years of GameDev.net! Share your GameDev Story with us.

• 14
• 12
• 29
• 11
• 45
• ### Forum Statistics

• Total Topics
634862
• Total Posts
3019682
×

## Important Information

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!