0

I am trying to create a program which would use a function to flip a coin, and using the Main() method, return the results of it landing on heads, tails, and its edge in a 2D array. There is a 40% chance of it landing on heads, 40% chance of it landing on tails, and a 20% chance of it landing on its edge.

I kind of have the function, but it does not change the number in the Main() method. What am I doing wrong? Any help would be appreciated.

#include <iostream>
#include <ctime>

using namespace std;

void coinToss();

int heads = 0, tails = 0, edge = 0;


int main(){
const int NUMROWS = 3;
const int NUMCOLS = 2;

srand(time(NULL));

coinToss();


cout << "Heads: " + heads << endl;   //just to check if function works properly

system("pause");
}

void coinToss(){
int flip = 0;
for (int i = 0; i<100; i++){
    flip = rand() % 10 + 1;
    if (flip < 4){
        heads++;
    } 
    else if (flip < 8){
        tails++;
    }
    else {
        edge++;
    }
}
}

1 Answers1

0

Your output line isn't correct:

cout << "Heads: " + heads << endl;

This is the same as

cout << ("Heads: " + heads) << endl;

which is the same as

cout << &("Heads: "[heads]) << endl;

which probably ends up with some kind of garbage due to heads being larger than seven. Instead, you have to use <<:

cout << "Heads: " << heads << endl;

Remarks

  • Don't use using namespace std.
  • If possible, use the C++11 <random> library instead of <cstdlib>'s rand.
  • Try to avoid global variables.
  • Head over to CR.SE to get further feedback as soon as you have a working program.
Community
  • 1
  • 1
Zeta
  • 103,620
  • 13
  • 194
  • 236