我正在尝试计算抛硬币中连续的正面朝上的次数。不幸的是,我的连续头计数器没有正确增加。有任何想法吗?代码和示例输出如下:
#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";
}
}
Output:
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.
每次致电FlipCoin(flip)
生成一个新的随机数。您调用它两次,因此它会生成两个不同的随机数。你应该打电话FlipCoin(flip)
一次并将其存储在变量中。
...
string result = FlipCoin(flip);
if (result == "heads") {
consecutiveHeads++;
} else
consecutiveHeads = 0;
}
cout <<"It took "<< totalFlips <<" coin flips to get 3 consecutive heads."<< endl;
...
正如其他人提到的,flip
你的变量main
未初始化且未使用。最好将其删除。建议你通过flip
作为你的参考FlipCoin
函数(使用&
)。这绝对有用途,但不是必需的。最简单的修改可能是:
string FlipCoin() {
if (randomChance(0.50)) {
return "heads";
} else {
return "tails";
}
}
PS:如果删除flip
来自函数的参数,您还必须替换每次出现的FlipCoin(flip);
with FlipCoin();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)