rand() - From A to B

Hello

I'm already familiar with the Rand() function,
rand () % 50;

But how exactly would I do these:
-Make rand() only use numbers from 5 to 10 (5,6,7,8,9,10)
-Make rand() only use numbers from 5 to 10 but NOT 8 (5,6,7,9,10)

And another question, does rand () % 50 prints number from 0-50, or 0-49?

Was just wondering.

Thanks for reading,
Niely
http://www.cplusplus.com/reference/cstdlib/rand/

Note: rand() is deprecated in latest standards. See <random>

The "NOT 8" is trickier. You could generate 5 to 9 and then add 1 if number is greater than 7.
> does rand () % 50 prints number from 0-50, or 0-49?
think of % as a remainder operator
Last edited on
-Make rand() only use numbers from 5 to 10 but NOT 8 (5,6,7,9,10)

if num is equal to 8 then add 1 or minus 1 ^^
@Lorence:
That would cause a non-uniform distribution. 7 or 9 would be more likely, due to the chance of 8 being an option.

@OP:
If you plan on having lots of different options, like the set of [1, 2, 3, 5, 6, 8, 10, 15] or something, then use an array:
1
2
int options[8] = {1, 2, 3, 5, 6, 8, 10, 15};
int choice = options[rand % 8];
Last edited on
Topic archived. No new replies allowed.