Why are my if statements not working consistently?

user3427139 picture user3427139 · Oct 7, 2014 · Viewed 10.2k times · Source

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.

Answer

Tony Delroy picture Tony Delroy · Oct 7, 2014

You're probably printing the output properly, then terminating without writing a newline on the last line, and your shell prompts clearing back to the left margin and overwriting your output (clearing the rest of the line to boot). If you have less than 10 tosses, your only line of output may appear lost, otherwise it'll be the last line.

Try adding an extra std::cout << '\n'; before main returns.

(Separately, you can say std::cout << "HT"[rand() % 2];, or std::cout << (rand() % 2 ? 'H' : 'T'); and do away with the ifs, but it's no big deal... whatever's clearest for you at this stage)