rand() returns a number from 0 to RAND_MAX. Therefore ((double)rand() / (double)(RAND_MAX + 1)) is a number in the range [0, 1). If you multiply this by the (integer) range of values you want (i.e. if you want a number from 2 to 5, the range is (5 - 2) + 1 = 4), then you get an integral value in the range [0, range). Now add the 'lowest' value that you want, in this case 2, and you'll have a value in the range of [2, 6). Since it's getting converted into an integer, the 6) gets truncated to 5], so you end up with a number in the range [2,5] as desired. So the formula is,
Code:
randomValue = (((double)rand() / (double)(RAND_MAX + 1)) * (highestValue - lowestValue + 1)) + lowestValue;
Now you can plug that into your program and substitute your own 'parameters' or values for highestValue and lowestValue so that x is assigned a random number in the range that you want.
Here's an example in code form:
Code:
int getRandomValue(int lowBound, int highBound)
{
//Find the number of possible values
int range = highBound - lowBound + 1;
//Get a random number from 0 to 1, excluding 1
double random_multiplier = (double)rand() / (double)(RAND_MAX + 1);
//Get a number from 0 to 'range', excluding 'range'
int tempVal = (int)(random_multiplier * range);
//Get a number from lowBound to highBound, including both
int randomVal = tempVal + lowBound;
return randomVal;
}
Hope this helps