Why are my C++ numbers not random?
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int randomNumber = rand() % 100;
for (randomNumber = 0; randomNumber < 20; randomNumber++)
{
cout << randomNumber << endl;
}
return 0;
}
//Why are my 20 numbers not random?
You need to use time() function as a seed in srand() and then use rand().
By the way you are not printing the rand() result, use this after the srand call:
You need to properly seed your random number generator, and then you need to repeatedly call rand() to get a new random number.
For example:
You're assigning randomNumber a random value, and then overwriting it with the numbers 0 through 19 in your for loop. Before your loop, you have a random number.
P.S. I hope this is a joke :(
You need to call rand() each time you want a random number. As you have it now you're generating one random number, then incrementing it and printing it out 20 times so you're going to get 20 sequential numbers.
Try something like
The seeding of the random number generator is important, without that you would generate the same numbers every time you ran the program.