I have been trying to generate a random number from 0 to 29. I've tried different methods from different sources to no avail.
Asked
Active
Viewed 154 times
-2
-
2https://www.google.com/search?q=c%2B%2B+generate+random+number – SLaks Mar 28 '19 at 15:08
-
4What have you tried? What happened? – SLaks Mar 28 '19 at 15:08
-
Taran, step one in figuring out coding questions is to do a google. I did a google of "c++ generate random number" and caught a bunch of good answers. This would have been MUCH faster than leaving questions here, especially as you're going to get a lot of people pointing you to the existing answers. – Joseph Larson Mar 28 '19 at 15:26
1 Answers
0
To generate random numbers in c++ you will neeed to include the <stdlib.h>
library.
#include <stdlib.h>
Start by intialising a seed. In this example we will use the system time (<time.h>
library) as a way to get a random seed initializer:
srand (time(NULL));
Now we create an integer variable:
int rNumber;
Finally we store the random generated number in the rNumber variable:
rNumber = rand() % 10 + 1;
Note that % 10 + 1
means that the generated random number will be between 1 and 10.
For more in formation on random number generation and a more in depth example refer to: http://www.cplusplus.com/reference/cstdlib/rand/

bruno echagüe
- 21
- 3
-
1Please don't recommend C solutions for C++ questions especially if there are better C++ answers. – Quimby Mar 28 '19 at 15:30