Question about this code

The code below is what I have so far. It's supposed to basically mimic a random coin flip where the user enters how many times he/she wants to flip the coin. However, my code doesn't seem to be all that random. If it's heads the first coin flip, then it's heads every time until the end of the program. And if it's tails first, then it's tails every time until the end of the program.

I'm basically confused as to why the program is acting like that, and not 100% random.

Thanks in advance for the help!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
  #include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

void coinToss();

int main()
{
    int flips;

    cout << "How many times would you like to flip a coin? ";
    cin >> flips;

    while (flips < 0)
    {
        cout << "Please enter a positive number of flips: ";
        cin >> flips;
    }

    for (int i = 1; i <= flips; ++i)
    {
        coinToss();
        cout << endl;
    }
}

void coinToss()
{
    unsigned seed = time(0);
    srand(seed);

    int toss = 1 + rand() % 2;

    if (toss == 1)
        cout << "Heads!";
    else
        cout << "Tails!";
}
You should only be seeding the random number generator (with srand) once in your program. Currently you are doing it every time you call coinToss, which will cause this kind of problem.
You are seeding the random number every time you call coinToss().

Move the following code to the beginning of main:
1
2
unsigned seed = time(0);
srand(seed);
Thank you! I put the seed in main, and it fixed the problem. Thanks again!
Topic archived. No new replies allowed.