-9

So, I made a coin flipping tool in C++, but the console always returns either every coin as Heads or every coin as Tails. Here's the code:

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

using namespace std;

int main() {
    srand(time(nullptr));
    int FLIP_RESULT = rand() % 2 + 1;
    int NUMBER_OF_FLIPS = 0;

    cout << "Welcome to Coin Flipper. How many coins would you like to flip?"
     << endl;

    cin >> NUMBER_OF_FLIPS;

    for (int COUNTER = 0; COUNTER < NUMBER_OF_FLIPS; COUNTER++) {
        if (FLIP_RESULT == 1) {
            cout << "Heads." << endl;
        } else if (FLIP_RESULT == 2) {
            cout << "Tails." << endl;
        } else {
            cout << "Error." << endl;
        }
    }
    return 0;
}

What's going on?

  • 2
    You only draw one random number and then check it `NUMBER_OF_FLIPS` times for being 1 or 2. You have to draw a new `FLIP_RESULT` after every check. – jotasi Apr 06 '18 at 11:00
  • @jotasi Ah, thank you. – WinterSunSummerSnow Apr 06 '18 at 11:02
  • 1
    *Why* are you using `srand/rand` that have horribly bad random properties, and not the facilities in the [](http://en.cppreference.com/w/cpp/numeric/random) header? `mt19937` and a `uniform_int_distribution` would seem to serve your purpose perfectly. – Jesper Juhl Apr 06 '18 at 11:10
  • @JesperJuhl Because I'm learning C++ from a book, and it taught me to use `srand/rand`. – WinterSunSummerSnow Apr 06 '18 at 11:11
  • 2
    @WinterSunSummerSnow - Hmm, maybe consider getting [a better book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list).. – Jesper Juhl Apr 06 '18 at 11:13
  • IMHO, `srand/rand` are fine as a starting point but, to me, the issue here is that you need to learn to use a debugger. – Bathsheba Apr 06 '18 at 11:28

1 Answers1

4

You declared:

int FLIP_RESULT = rand() % 2 + 1;

at the start of your code. This means that the flip happens only once at the start of the program, regardless of the number of flips the user inputs.

Try randoming the FLIP_RESULT as first line of your for loop, and you'll see it working.

git_gud
  • 649
  • 1
  • 11
  • 27