OK, most probably it will be marked as duplicated, but I am looking for an answer and cannot find something similar. The question is: I want to generate random numbers within a specific range [i.e. min_value to max_value] and with a specific step. For the first part the answer is:
int random_value = rand() % max_value + min_value;
The step how can I define it? I suppose that the above mentioned solution results in step 1. Correct? And if for example I want to generate the numbers with step 2 (e.g. 2, 4, ..., 16) what should I do?
Your "first step" is ill-advised since it suffers from modulo bias.
Introducing a "step" is a matter of simple arithmetic, you generate a random number on a smaller range
min_value / step
tomax_value / step
and multiply that by your required step (random_value * step
).So:
This should do what you want: