Reputation: 390
I want to generate a random float value between 0 and 1 excluding 1, I.e. [0, 1)
. I've searched a lot but I couldn't find an answer of this. I've tried the following trick however it generates a negative values
(double)rand()/(double)RAND_MAX-1;
Upvotes: 0
Views: 1139
Reputation: 4369
You just need to divide by RAND_MAX including +1. Like this:
(double)rand()/((double)RAND_MAX+1);
Upvotes: 1
Reputation: 96258
You need parentheses to force the right order:
(double)rand()/((double)RAND_MAX + 1);
Also note, that you need +1, not -1.
Upvotes: 2