I was looking for C code to generate a set of random even number in range [start, end]. I tried,
int random = ((start + rand() % (end - start) / 2)) * 2;
This won't work, for example if the range is [0, 4], both 0 & 4 included
int random = (0 + rand() % (4 - 0) / 2) * 2
=> (rand() % 4 / 2) * 2
=> 0, 2, ... (never includes 4)
On the other hands if I use,
int random = ((start + rand() % (end - start) / 2) + 1) * 2;
This won't work, for example,
int random = (0 + rand() % (4 - 0) / 2 + 1) * 2
=> (rand() % 4 / 2 + 1) * 2
=> 2, 4, ... (never includes 0)
Any clue? how to get rid of this problem?
Aucun commentaire:
Enregistrer un commentaire