Need some help on Cointoss !!

So this program suppose to let user insert how many times they want to toss the coin and then the program will generate random numbers between 1 -2 , 1 for head, 2 for tails. and in the end display the total amount of heads and tails. But when I run this program that I wrote I always get all tails or all heads, for exanple if I input 5 to toss the coin 5 times its always either 5 tails or 5 heads, please help !

Here is my program:

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int headcount;
int tailcount;
int cointoss();

int main()
{
int numberoftoss;

cout<<"How many times would you like to toss the coin ? Insert a number : ";
cin>>numberoftoss;

cointoss();


int variable1;


for(variable1=0; variable1<numberoftoss; variable1++)



if(cointoss() == 1)
{
headcount++;

}
else
{
tailcount++;
}

cout<<headcount<<" heads."<<endl;
cout<<tailcount<<" tails."<<endl;



return 0;
}


int cointoss()
{
int value1;
srand(time(0));
value1= rand() % 2 +1;

return value1;
}
Last edited on
You are calling srand() every time you want a new random number. This sets the starting point in the random number sequence based on current time and this won't change sufficiently to give different numbers at successive calls.

Move the srand() call out of cointoss and put it at the start of main() so that it is called only once.

The single call to cointoss() outside the for loop (after your cin statement) is also redundant.

Please use code tags so that we can refer to line numbers and test your code. The formatting menu may not work on first post, but you can always put them in by hand or edit your post immediately after submission.
Last edited on
Thanks, it worked !
closed account (48T7M4Gy)
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
#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int cointoss();

int main()
{
    int headcount = 0;
    int tailcount = 0;
    int numberoftoss = 0;
    
    cout<<"How many times would you like to toss the coin ? Insert a number : ";
    cin>>numberoftoss;
    
    srand(time(0)); // <--
    
    for(int variable1=0; variable1<numberoftoss; variable1++)
    { // <--
        if(cointoss() == 1)
        {
            headcount++;
        }
        else
        {
            tailcount++;
        }
    }// <--
    
    cout<<headcount<<" heads."<<endl;
    cout<<tailcount<<" tails."<<endl;

    return 0;
}


int cointoss()
{
    int value1;
    value1= rand() % 2; // <--
    return value1;
}
Last edited on
Topic archived. No new replies allowed.