C Random Number Generation – Generate Random Number in C Within a Range and Specific Step

c++random

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?

Best Answer

This should do what you want:

int GetRandom(int max_value, int min_value, int step)
{
    int random_value = (rand() % ((++max_value - min_value) / step)) * step + min_value;
    return random_value;
}
Related Question