What is wrong with my code? There is an error at {. Its after else.

//Coin Toss. Coin Toss.cpp
//Program designed to simulate coin tossing
#include <iostream>
#include <cstdlib>

using namespace std; //To include std infront of all cout and cin
int main()
{
//Variable declaration
int coin;//Coin is having two sides which are heads and tails
int heads;//Heads is one of the side of the coin
int tails;//Tails is another side of the coin
int counter;

//Initialization phase
heads = 0;//Initializing heads equals zero
tails = 0;//Initializing tails equals zero
for ( counter = 0; counter <= 100; counter++)
{
if (coin == 1)
{
cout<<"H"<<endl;//Display H as heads
heads = heads + 1;//Formula to calculate number of heads
}
else (coin == 0 )
{
cout<<"T"<<endl;//Display T as tails
tails = tails + 1;//Formula to calculate number of tails
}
}

cout<<"The total number of heads is:"<<heads<<endl;//Display the number of heads
cout<<"The total number of tails is:"<<tails<<endl;//Display the number of tails
}











First of all, to make code easier to read for people who want to help you, please use code tags. The little http://www.cplusplus.com/ico/text_code.png icon under format next to your text box when you are creating your thread will do that.

The solution to your problem is to use else if (coin==0)

The else statement will only execute the the next block of code if the if statements that it is attached to evaluates to false. You need to say: if my if statement is true do this, else check and see if this is true.
Last edited on
Can you please teach me how to include srand????
srand( (unsigned) time(NULL) );

http://www.cplusplus.com/reference/cstdlib/srand/?kw=srand
http://www.cplusplus.com/reference/cstdlib/rand/

You should call srand only once to get the seed at the beginning of your program and then call rand() when ever you want a random number. You will want to use the modulus operator though.
Last edited on
closed account (Dy7SLyTq)
yeah you only need to call srand once because it sets a global variable (i think called seed) that rand uses to return a random int. i would recommend <random> or whatever the new c++11 one is
On a side note a pseudo random number generator (PRNG) are really just sequences of numbers. The formula for them I believe is something like
a0 = seed
an = (an-1 * r + b) % m
Where n is the number of sequences , r is a rate you choose , b is a number to increase and m is the number you are taking the modulus of ( max value )
Topic archived. No new replies allowed.