RandBetween


return to main index


#include <stdlib.h>


Random numbers, well actually pseudo random numbers, can be generated using the rand() function. Unfortunately, rand() generates integer values in the range 0 to RAND_MAX, where RAND_MAX is a macro that defines the largest value that rand() can generate. Often we want to generate random floating point numbers between a minimum and a maximum value.

Here is the code for a function that can do just that.

double randBetween(double min, double max)
{
 return ((double)rand()/RAND_MAX) * (max - min) + min;
}

Notice the use of casting or promotion "double)rand()". This ensures that when we divide the integer returned from rand() by RAND_MAX we get a floating point value - without this we would only get zero's or one's because the result of dividing an integer by a number is an integer. Remember to add the #include <stdlib.h> statement to your 'C' source code file.

In the 'C' language 3 divided by 2 gives 1 not 1.5 because 3 is an integer!!


© 2002-4 Malcolm Kesson. All rights reserved.