Hello everyone,
I am a beginner with C++ and I am unsure of where to use srand() and rand().
So what I am trying to do is have srand(time(0)) in my main program, and rand() in another part of my program which I called "driver()".
I read somewhere that srand(time(0)) would give you a random set of numbers each time you use the program and srand(1), or any positive number, would give you the same information each time. Or at least that is how I understood it.
It's for a coin tossing program, so here is what I did..
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
int main()
{
cout << "Do you wish to play the coint tossing game (y/n)? ";
cin >> res;
cout << endl;
srand(time(0));
while (res == "y")
{
cout << "Run " << runs << endl << endl;
driver();
cout << "Do you want to play again? (y/n) ";
cin >> res;
runs++;
cout << endl;
}
}
|
So in my mind, this is calling srand(time(0)) once since the program never goes back to the top of main(). Here is my rand() portion of the code which is in my function void driver().
1 2 3 4 5 6 7 8 9
|
while ( count < flipcount )
{
int toss = rand() % 2; //You will get the value 0 or 1
if ( toss == 0 )
heads++;
else
tails++;
count++;
}
|
So whenever I run the program, I get the same output every time. And If I put a number too big than it just spits out garbage. So my question is what am i doing wrong?