我正在尝试在掷硬币时数连续的正面。不幸的是,我的连续正面计数器没有正确增加。有任何想法吗?下面的代码和示例输出:
#include <iostream>
#include <string>
#include "random.h"
using namespace std;
string FlipCoin (string flip);
int main() {
string flip;
int consecutiveHeads = 0;
int totalFlips = 0;
while (consecutiveHeads<3) {
totalFlips++;
if (FlipCoin(flip) == "heads") {
consecutiveHeads++;
} else {
consecutiveHeads = 0;
}
cout <<totalFlips<<" "<< FlipCoin(flip) << " " << consecutiveHeads <<endl;
}
cout <<"It took "<< totalFlips <<" coin flips to get 3 consecutive heads."<< endl;
return 0;
}
string FlipCoin(string flip) {
if (randomChance(0.50)) {
return "heads";
} else {
return "tails";
}
}
输出:
1 heads 1
2 tails 0
3 tails 1
4 heads 2
5 heads 3
It took 5 coin flips to get 3 consecutive heads.