How to generate random float numbers within a range (not from 0) in C?
I tried the code mentioned at this link : How to generate a random number from within a range . But this one always returns a "1" when I pass in maximum - minimum +1.
Thanks.
How to generate random float numbers within a range (not from 0) in C?
I tried the code mentioned at this link : How to generate a random number from within a range . But this one always returns a "1" when I pass in maximum - minimum +1.
Thanks.
Try this:
#include <time.h>
#include <stdlib.h>
float GetRand(float min,float max)
{
static int firstTime = 1;
if (firstTime == 1)
{
firstTime = 0;
srand((unsigned int)time(NULL));
}
return (max-min)*rand()/RAND_MAX+min;
}
Please note that this function is not thread-safe, so you may want to call srand
beforehand.