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?

2

1 Answer 1

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;
Sign up to request clarification or add additional context in comments.

1 Comment

Using modulo introduces bias (look up the "pidgeon hole principle"). Better to use std::uniform_int_distribution.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.