2

我正在尝试在掷硬币时数连续的正面。不幸的是,我的连续正面计数器没有正确增加。有任何想法吗?下面的代码和示例输出:

#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.
4

3 回答 3

0

每次调用FlipCoin函数时都会翻转。因此,您在while函数的每次迭代中翻转两次。您可以考虑flip作为参考传递FlipCoin

#include <iostream>
#include <string>
#include "random.h"
using namespace std;

void FlipCoin (string &flip);


int main() {
    string flip;
    int consecutiveHeads = 0;
    int totalFlips = 0;
    while (consecutiveHeads<3) {
        totalFlips++;
        FlipCoin(flip);
        if (flip == "heads") {
           consecutiveHeads++;
        } else {
            consecutiveHeads = 0;
        }
        cout <<totalFlips<<" "<< flip << " " << consecutiveHeads <<endl;
    }
    cout <<"It took "<< totalFlips <<" coin flips to get 3 consecutive heads."<< endl;
    return 0;
}


void FlipCoin(string &flip) {
    if (randomChance(0.50)) {
        flip = "heads";
    } else {
        flip = "tails";
    }
}
于 2013-09-02T05:42:21.970 回答
0

每次调用都会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);FlipCoin();

于 2013-09-02T05:44:03.747 回答
0

问题是您FlipCoin()在每次迭代中调用了两次:首先与 进行比较"heads",然后再次显示发生了什么。您需要调用一次,并将其放入变量中:

while (consecutiveHeads<3) {
    totalFlips++;
    string curFlip = FlipCoin(flip);
    if (curFlip == "heads") {
       consecutiveHeads++;
    } else {
        consecutiveHeads = 0;
    }
    cout <<totalFlips<<" "<< curFlip << " " << consecutiveHeads <<endl;
}

PS 的论据是FlipCoin()什么?

于 2013-09-02T05:44:11.133 回答