#include <iostream>
#include <windows.h>
#include <cstdlib>
#include <ctime>
usingnamespace std;
int randomNumber(int a);
int main(){
int num = randomNumber(4);
for(int x = 0; x < 25; x++){
num = randomNumber(4);
cout << num << endl;
}
}
int randomNumber(int a){
srand(time(0));
int num = rand()%a;
return num;
}
Line 28: Do not call srand() within a loop or a random number function. srand() sets the RNG to a particular starting point. Calling srand() repeatedly can cause the RNG to return the same random numbers. srand() should be called ONCE at the beginning of main(). http://www.cplusplus.com/reference/cstdlib/srand/
The srand() function sets its argument as the seed for a new sequence of pseudo-random integers to be returned by rand(). These sequences are repeatable by calling srand() with the same seed value.
You seed the pseudo random number generator each time you call your function, you reset the generator within a very short period of time, ending up with the same sequence of un-random numbers.
#include <iostream>
// #include <windows.h> // not needed for this!
#include <cstdlib>
#include <ctime>
int randomNumber(int a);
int main()
{
// seed the random generator ONCE
srand(time(0));
int num = randomNumber(4);
for(int x = 0; x < 25; x++)
{
num = randomNumber(4);
std::cout << num << " ";
}
std::cout << "\n";
}
int randomNumber(int a)
{
int num = rand() % a;
return num;
}
The C library random functions are inefficient, have horrible distribution and grossly outdated. C++ has much better random number generation utilities in <random>:
#include <iostream>
#include <chrono>
#include <random>
int main()
{
// obtain a seed from the system clock:
unsigned seed = static_cast<unsigned> (std::chrono::system_clock::now().time_since_epoch().count());
// seeds the random number engine, the standard default random engine
std::default_random_engine generator(seed);
// discard some values for better randomization
generator.discard(generator.state_size);
// set a distribution range (0 - 3)
std::uniform_int_distribution<int> distribution(0, 3);
for (int loop = 0; loop < 25; loop++)
{
// pick and store the random number
int numPicked = distribution(generator);
std::cout << numPicked << " ";
}
std::cout << "\n";
}
Even the C standard (footnote 295) recommends NOT using rand():
There are no guarantees as to the quality of the random sequence produced and some implementations are known to produce sequences with distressingly non-random low-order bits. Applications with particular requirements should use a generator that is known to be sufficient [read: not this one] for their needs. (emphasis added)