srand funtion

Apr 26, 2017 at 4:14am
#include<iostream>
#include<ctime>
#include<cstdlib>
using namespace std;
int random ()
{
int rand_num;
srand(time(0));
rand_num=rand()%6;
return rand_num;
}


main()
{
for (int i=0;i<=5;i++)
{
cout<<random();
}

}

//prog: print the same values as 555555, 111111 ,000000, etc.
// Result Requried is that it print random values at once (in one execution).
//REquried RESULT: 012321 , 021231 etc
please help ..
Apr 26, 2017 at 4:50am
Your code is calling srand() multiple times. That is a problem, as it will almost certainly use the same seed each time, and thus resets the sequence to generate the same pseudo-random number.

Move the call to srand() out of function int random (). Instead, call it just once at the start of main().
Apr 27, 2017 at 10:24am
Thanks it works
Topic archived. No new replies allowed.