+ 2
Random number generator?
How can I make a c++ program that generates a random number between 1 and 10 and generates a new number each time the program runs. I was able to make it generate a random number, but it was the same every time I ran the program.
3 Answers
+ 2
You need to use the function srand(time(0)) to make so that the algorythn will generate random number based on the system clock, so you will have a different number everytime:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main () {
srand(time(0));
for (int x = 1; x <= 10; x++) {
cout << 1 + (rand() % 10) << endl;
}
}
The above code will output random number between 1 and 10
To use the time() func you need to implement the header <ctime>!
+ 2
0
Yes, nice job!