-
repeated random
my problem is i designed a simple true/false test for one of my teachers and the questions are supposed to be random and not repeat themselves but i am constantly getting repeated numbers and i don't know why
Code:
int main(void)
{
srand((unsigned)time(NULL));
cout << "Randomized Safety Test v1.2.2\n\nPlease answer all question with a true(1) or false(0) answer.\n\n";
do
{
int question = rand()%48;
switch(question)
{case 1:// Question 1
if(q1==0)
{
cout << count + 1 << ") ESD is another term for static electricity.\n"
<< " 0) false\t 1) true\n";
cin >> answer;
count++;
int q1 = q1+1;
if (answer == 1)
{
score = score + 4;
cout << "\n";
}
else
cout << "\n";
break;
}
else
{
break;
}
int q1 is the variable i tryed to use to keep my questions from repeating
-
I really can't see anything wrong in there...all I can think of is try initializing q1 at the top, instead of initializing it everytime through the loop....post all your code and maybe we'll be able to help out more.
-
Code:
int main(void)
{
srand((unsigned)time(NULL));
int question = rand()%48;
cout<<question<<endl;
return 0;
}
I ran that code on my computer repeatedly, and I couldn't get the same number to come up. Is your system clock working?
Also, my book says using rand()%count to get a value between 0 and count will effectively truncate the value returned from rand() to a few low order bits, and because of the way pseudo-random numers are generated, these many not be random. For your purposes, I don't think it really matters though.
Did you remember to use
break;
as the last line for every case?
-
You have to set srand(time(NULL)); to NULL in every loop in case to get different random numbers.
Here's a code, that is working perfectly in one of my programs:
Code:
ln=countln(ln); //
srand(time(NULL)); //randomization
i_gotoln=rand()%ln; //
:)
-
Calling srand() more than once in a program will give you bad random numbers, most importantly because the speed of computers will often times call srand() many times within milliseconds or less of each other if placed in a loop causing very little difference in the next random number called.
xDeath, you have srand in the correct spot. Without the rest of the code though its tough to see why the same question is asked over and over again. From what I can see it should just work fine with out the variable q1.
-
Try everything... but...
At this point xdeath should probably try EVERYTHING, but normally, you should NOT have to seed the random number generator more than once.
xdeath,
Try displaying the value of time(NULL). If it's always the same value, rand() may also always be the same value.
[EDIT]
PJYelton is right! If you don't wait more than 1ms before re-seeding... you're going to get the same number again. Definately NOT random. (Not even psudo-random.) So, I take that back... DON'T TRY EVERYTHING! :)