So in the code below when I run the program the random
number is outputting in sequence. Meaning every time I
press run, I get 3, 6, 8, 12, 19, 2, 4, 7 (out of 20) etc.
I was just wondering why that was. Thanks for any answer.
// These are the only preprocessor directives you need.
#include <iostream> // For input/output functions.
#include <cstdlib> // For the random function.
#include <ctime> // For time.
usingnamespace std;
int main()
{
//This is fine.
srand(time(0));
//I'm guessing you want to store your random numbers into an array.
//So this declares an array that can hold 10 elements.
int randNum[10];
//This loop sets each element (10 elements) to random numbers of between 1-20.
for(int x=0; x<10; x++){
randNum[x] = 1+(rand()%20);
}
//This loop goes through each element and displays them.
for(int x=0; x<10; x++){
cout << randNum[x] << endl;
}
//And you don't need a return in main in the latest C++...
}
Each time you run the program are seeding RNG with increasing values (as time in going forward)
Depending on rand() implementation it might first return current state and then advance, meaning that first call to rand() will just return seed.
MinGW Gcc does that, I just tested.
Basically srand(time(0)); is bad randomizer. At least advance generator once before actually using it.
I just left the preprocessor's in from a current program I'm working on and took everything else out. I just want to output a random number. Currently I am getting the numbers in sequence like 3, 6, 9, and so on. I always thought that this func generated numbers NOT in sequence but just found that it did and wondered why that was that's all.
What do you want to do?
To return a random number from a function.
Yea really :) I don't see why your random numbers are appearing in a sequence. This code works fine for me, It returns 1 random number within the range of 1 to 20 to the function.
1 2 3 4 5 6
int RandomNumber(){
srand(time(0));
int randNum;
randNum = 1+(rand()%20);
return randNum;
}
I don't usually use rand() like that. I didn't know you could. I usually make a program like this and it always works fine for me:
1 2 3 4 5 6 7 8
int RandomNumber(){
srand(time(NULL)); //I use NULL instead of 0, just the way I was taught
int randNum;
randNum = rand() % 20 + 1;
//Instead of putting rand() and 20 inside parenthesis, I just do this.
return randNum;
}
I do that and it works. I also tried your code and, like ALEXCX2PLUS, I wasn't getting a sequence. Maybe your compiler or something...
I'm guessing it's my compiler too. I tried ALEXCX2PLUS code snippet also and kept getting random numbers in sequence. What helped was when I initialize the variable holding the random num twice. See below..
For some reason, initialzing "randomNumber" twice breaks the sequence and gives me randomness. I'll take it...I've made games with this rand num generator and have never run into this problem. I think it's the new codeblocks/mingw/compiler.