Reputation:
Write a program that simulates flipping a coin repeatedly and continues until three consecutive heads are tossed.
#include <iostream>
#include <cmath>
#include <string>
#include <cstdlib>
#include "random.h"
using namespace std;
enum CoinSide {heads, tails};
CoinSide FlipCoin(int flip);
int main(){
int flip;
int heads = 0;
int total_flips = 0;
while( heads < 3){
total_flips++;
if(FlipCoin(flip) == heads){
heads++;
} else{
heads = 0;
}
}
cout << "it took " << total_flips << "to get 3 consecutive heads. " << endl;
}
CoinSide FlipCoin(int flip) {
if (randomChance(0.50)) {
return "heads";
} else {
return "tails";
}
}
Now I am getting an unknown error, when I run this code, anyone know why it wont run>?
Upvotes: 0
Views: 1013
Reputation: 114
Apart from the above answer:
Please do yourself and anybody who might have to look over your code a favor by never ever using the same name for different things and try to use those different things in the same context. In this case I'm talking about
enum CoinSide {heads, tails}; // <- This
CoinSide FlipCoin(int flip);
int main(){
int flip;
int heads = 0; // <- in combination with this! Because:
int total_flips = 0;
while( heads < 3){
total_flips++;
if(FlipCoin(flip) == heads){
// You might think you're comparing
// FlipCoin(int)::CoinSide vs. CoinSide::heads
// But(!) you compare
// FlipCoint(int)::CoinSide vs. main::heads
// The very main::heads you're going to increase now.
heads++;
} else{
heads = 0;
}
} // Will never terminate.
cout << "it took " << total_flips << "to get 3 consecutive heads. " << endl;
}
If you use constant values which mean something you should
a) make them visually stand out, e.g. using HEADS or TAILS instead of heads or tails in enums. b) never ever give two things the same name and (try to) use them in the same context.
This will save you some serious case of head scratching in the future.
Upvotes: 1
Reputation: 258608
FlipCoin
returns a boolean (integral) value, and comparison against a const char*
is illegal. "heads"
and "tails"
are just that.
You can return a std::string
to perform a comparison, but I'd suggest you have an enum CoinSide {HEADS, TAILS};
and return that instead.
CoinSide FlipCoin(int flip) {
if (randomChance(0.50)) {
return HEADS;
}
return TAILS;
}
and
if (FlipCoin(flip) == HEADS)
Upvotes: 3