### Need help generating random number.

Hi guys

I'm quite new to C++, I'm trying to generate a random number between 1 and 10 (meaning 1 and 10 is excluded from the random number), but I'm having some difficulty achieving that. The following code produces a random number between 0 and 10, but I need the number 1 to be excluded, thus generating a random number consisting of 2 to 9, but I don't know how to do that. Thanks in advance.

 ``123456789101112131415161718192021`` ``````#include #include #include using namespace std; int main() { int Highest = 10; int Lowest = 1; int RandomNumber; srand(time(0)); RandomNumber = rand() % Highest; cout << RandomNumber << endl; return 0; } ``````
Last edited on
The modulo operator (%) gives you the remainder after division.
This means that `X % Y` will always give you a number between [0,Y) (assuming X and Y are both > 0)

 ``123`` ``````(rand() % 5) ... [0,5) (rand() % 5) + 1 ... [1,6) (rand() % 5) + 2 ... [2,7)``````

etc.

You are looking for (1,10) ... or [2,10). Which means you want:

 `` `` ``(rand() % 8) + 2 ... [2,10)``

This basically works out to
 ``1234567`` ``````// highest is exclusive // lowest is inclusive // so [lowest, highest) int range = highest - lowest; int random = (rand() % range) + lowest;``````

EDIT:

Or if this is C++11...

 ``1234567891011`` ``````#include #include int main() { std::default_random_engine rng( static_cast( time(nullptr) ) ); std::uniform_int_distribution dist(2,9); // inclusive [2,9] int randomNumber = dist(rng); }``````
Last edited on
That helped alot, thank you =]
Topic archived. No new replies allowed.