0

I am trying to generate random numbers between 2 and 11, here is my code:

srand(time(NULL));

int card;
card = rand() % 11 + 2;

However, currently my code is creating numbers from 2-12. How could I solve this so that it creates numbers from 2-11?

Pauline
  • 5
  • 3
  • 5
    Does this answer your question? [Generating random integer from a range](https://stackoverflow.com/questions/5008804/generating-random-integer-from-a-range) – NutCracker Jan 23 '20 at 18:46
  • 1
    What you want is [std::uniform_int_distribution](https://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution). And *please* stop using `rand()` in new code. – Jesper Juhl Jan 23 '20 at 19:36

1 Answers1

3

range % 11 has 11 possible vales (0 to 10), but you want 10 possible values (2 to 11), so you first change your mod to % 10. Next, since the values returned by rand() % 10 start at 0, and you want to start at 2, add 2. So:

card = rand() % 10 + 2;
stark
  • 12,615
  • 3
  • 33
  • 50
  • Using modulo introduces bias (look up the "pidgeon hole principle"). Better to use [std::uniform_int_distribution](https://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution). – Jesper Juhl Jan 23 '20 at 19:38