RandBetween#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.
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.
|
© 2002-4 Malcolm Kesson. All rights reserved.