C ++硬币翻转程序错误

时间:2013-09-02 05:38:25

标签: c++ flip

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

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

3 个答案:

答案 0 :(得分: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";
    }
}

答案 1 :(得分: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();

答案 2 :(得分:0)

问题是你在每次迭代中调用FlipCoin()两次:首先与"heads"进行比较,然后再次显示发生的事情。你需要调用一次,并把它放在一个变量中:

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

P.S。 FlipCoin()的论点是什么?