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

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

最佳答案

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

关于c++ - C++投币程序错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18566294/

10-11 22:35