Problem with Srand.

Hey guys, I have a coin toss simulation I am trying to run, but the problem is I keep getting only one result instead of a randomized one. I went over the code and it doesn't seem like anything would be out of place. I was hoping for some tips to the problem.

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
41
42
43
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;

int Flip();

int main()
{

	int Heads = 0;
	int Tails = 0;
	int num;

	for (int i = 0; i < 100; i++)
	{
		num = Flip();
		if (num == 1)
		{
			cout << "Heads" << endl;
			Heads++;
		}
		else
		{
			cout << "Tails" << endl;
			Tails++;
		}

	}

	cout << "Total amount of Heads is " << Heads << endl;
	cout << "Total amount of Tails is " << Tails << endl;

	return 0;
}

int Flip()
{
	int num;
	srand((unsigned) time(0));
	num = rand() % 2;
	return num;
}
The random seed should only be initialized once in the lifetime of your program.

Move line 40 to the beginning of main.
Ahh, yea that'd do it. thanks.
closed account (1CfG1hU5)
yes agree, srand func early to initialize random generator. if called more than once, srand() will
be active throughout all of main. also:

1
2
3
4
5
6
7
8
9
10
11
12
13
num = rand() % 2 + 1;  // to get 1 or 2 only
                                    // sometimes rand() will exceed expected
                                    // did rand() %14+2 before and was getting 15

or could do

num = rand() %1;  // where 0 is head and 1 is tails or the opposite

or random(2) could be used

random does (num -1)

an example in one of my languages is random(100), 0 to 99

Last edited on
Topic archived. No new replies allowed.