Search code examples
c++if-statementcoin-flipping

Why are my if statements not working consistently?


I'm making a coin toss program for my c++ class and we are required to make a function that flips a coin and prints out if it is heads or tails, and print 10 per line. When I ran the program though the if statements I used to detect if the coin was heads or tails weren't enough to pick from the two.

#include <iostream>
#include <ctime>
using namespace std;

void coinToss(int times);

int main()
{
srand(time(0));
    int times;
    cout << "How many times would you like to toss the coin?" << endl;
    cin >> times;

coinToss(times);

return 0;
}

void coinToss(int times)
{
    int toss = 0, count = 0;
    for(int i = 0; i < times;i++)
    {
        toss = rand()%2;

        if(toss == 1)//Detects if coin is heads.
        {
            cout << "H";
        }
        if(toss == 0)//Detects if coin is tails.
        {
        cout << "T";
        }

        else //I had to include this for the program to run, further explanation below the code.
        {
        cout << "Ya done goofed."; 
        }

        count++; //Counts to ten
        if(count == 10) //Skips to the next line if the coin has been tossed ten times.
        {
            cout << endl;
            count = 0;
        }
    }

}

At one point I replaced the heads or tails with "cout << toss;" and the only numbers returned were 1 and 0. I don't understand how if I'm getting only the two numbers I'm checking for some of them aren't being caught by my if statements.

To complete the assignment I've changed the second if statement into an else statement and everything seems peachy, but I'd really like to understand what's going on here.


Solution

  • What happens with your code is:

    Is the result 1 ? Then print H. Keep going. Is the result 0 ? Then print T. Else, if it's not 0, print "Ya done goofed.".

    You need to keep your if statements linked together:

    if (toss == 1) {
        cout << "H";
    } else if (toss == 0) {
        cout << "T";
    } else {
        cout << "Ya done goofed.";
    }

    You won't fall in the else case anymore and will be able to remove it.

    As a sidenote, regarding your overall program structure: your coinToss function shouldn't do everything. Your code should be more splitted: a function which returns H or T, a function which calls this function X times as requested by the user and formatting the output would be a good start.

    Another small note: your count variable, allowing you to add a new line every 10 flips, could be removed. i % 10 will give you the same result: every ten increments, i % 10 would be equal to 0.