Weird Rand() problem

This is a coin toss program. Every time I run the program it will give either all heads or all tails. It's never a mixture of both. Is it only seeding the generator once?


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
44
45
46
47
48
49
50
51
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;

//func prototype*******************************************************
int coinToss();
//*********************************************************************

int main()
{
	int num,
		headsTails;

	cout << "How many times would you like to run the coin toss?" << endl;
	cin >> num;

	for (int count = 0; count < num; count++)
	{
		headsTails = coinToss();

		if (headsTails == 1)
		{
			cout << "The computer picked Heads." << endl;
		}

		else 
		{
			cout << "The computer picked Tails." << endl;
		}

	}

	return 0;
}

//func header**********************************************************
int coinToss()
{
	int num,
		max = 2,
		min = 1;

	int range = max - min + 1;

	srand(time(NULL));
	num = rand() % range + min;

	return num;
}
//********************************************************************* 
Last edited on
You're seeding the random number generator with the same value each time, because the time doesn't change quickly enough, so you're generating the exact same "random" value every time.

Seed the random number generator ONCE only.

https://stackoverflow.com/questions/5574914/srandtimenull-doesnt-change-seed-value-quick-enough
Last edited on
If i seed once in main , will rand in the function work? Without passing anything as an argument?
Well, i guess it does. Thanks haha
Topic archived. No new replies allowed.