Each call to FlipCoin(flip)
generates a new random number. You call it twice, so it's generating two different random numbers. You should call FlipCoin(flip)
once and store it in a variable.
...
string result = FlipCoin(flip);
if (result == "heads") {
consecutiveHeads++;
} else
consecutiveHeads = 0;
}
cout <<"It took "<< totalFlips <<" coin flips to get 3 consecutive heads."<< endl;
...
As somebody else mentioned, the flip
variable in your main
is uninitialized and unused. It's best to remove it. It was suggested that you pass flip
as a reference in your FlipCoin
function (using &
). This most definitely has uses but it's not necessary. The simplest revision might be:
string FlipCoin() {
if (randomChance(0.50)) {
return "heads";
} else {
return "tails";
}
}
PS: If you remove the flip
parameter from the function, you must also replace every occurence of FlipCoin(flip);
with FlipCoin();