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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <cstdlib>
#include <ctime>

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)

From there, you can just add values to your generated number to adjust it:
1
2
3
(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
1
2
3
4
5
6
7
// 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...

1
2
3
4
5
6
7
8
9
10
11
#include <random>
#include <ctime>

int main()
{
   std::default_random_engine rng( static_cast<unsigned>( time(nullptr) ) );

   std::uniform_int_distribution<int> dist(2,9);  // inclusive [2,9]

   int randomNumber = dist(rng);
}
Last edited on
That helped alot, thank you =]
Topic archived. No new replies allowed.