Generate random number in C within a range and a s

2019-02-23 07:42发布

问题:

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?

回答1:

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;
}


回答2:

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 to max_value / step and multiply that by your required step (random_value * step).

So:

#include <stdint.h>
#include <stdlib.h>
int random_range( int min_value, int max_value )
{
    // Fix me
    return rand() % max_value + min_value;
}

int random_range_step(  int min_value, int max_value, int step )
{
    return random_range( min_value / step, max_value / step ) * step ;
}

...

//  (e.g. 2, 4, ..., 16)
int random_value = random_range_step( 2, 16, 2 ) ;


标签: c random