我试图制作一个C ++程序来计算我连续输入的相同类型的硬币投掷数量,但结果很奇怪。我试图把它折腾了1,000,000次而且我没有得到比15更多的“相同类型的投掷”。我在较少数量的投掷(5-20)上测试它并且它似乎正常工作,除了我也连续不超过15个。
#include <iostream>
#include <ctime>
#define LOOP 1000000//how many times do I toss a coin
int main()
{
int maxTails = 0, maxHeads = 0, currentTails = 0, currentHeads = 0, totalHeads = 0, totalTails = 0;
int totalMax = 0;//highest amount of "in a row" out of all iterations
bool heads = false;//last toss
srand(time(0));
for (int x = 0; x < 100; ++x) {//this is to increase the amount of how many times I want to toss a coin LOOP times
for (int i = 0; i < LOOP; ++i)//tosses a coin LOOP times
{
if (rand() % 2 == 0)// heads
{
if (heads == false)//if last toss was tails I check if the "in a row" for it was more than the current maximum
{
if (currentTails > maxTails) maxTails = currentTails;
currentTails = 0;
currentHeads = 0;
heads = true;
}
currentHeads++;
totalHeads++;
if (currentHeads > maxHeads) maxHeads = currentHeads;
}
else//tails
{
if (heads == true)
{
if (currentHeads > maxHeads) maxHeads = currentHeads;
currentHeads = 0;
currentTails = 0;
heads = false;
}
currentTails++;
totalTails++;
if (currentTails > maxTails) maxTails = currentTails;
}
}
if (maxTails > totalMax) totalMax = maxTails;//totalMax is the maximum "in a row" of either tails or heads
if (maxHeads > totalMax) totalMax = maxHeads;
std::cout << "Throws: " << LOOP << ", Total heads: " << totalHeads << ", Total tails: " << totalTails << ", Maximum heads: " << maxHeads << ", Maximum tails: " << maxTails << std::endl;//writes all the info
//std::cout << "Iteration: " << x + 1 << ", Max: " << totalMax << std::endl;
maxTails = maxHeads = currentHeads = currentTails = totalHeads = totalTails = 0;
}
std::cout << "Max: " << totalMax << std::endl;
system("pause");
return 0;
}
我在互联网上看过,如果你把硬币投入1,000,000次,那么有大约38%的几率连续获得20个筹码,但我的节目的工作方式不同。我的代码中是否存在问题,或者rand()函数可能存在问题?
答案 0 :(得分:1)
阅读@BathSheba评论。期望与现在不同的输出是不准确的。
为了简单起见,读者可以根据需要进行调试,这是您的代码的工作版本:
#include <iostream>
#include <ctime>
#define LOOP 1000000 //how many times do I toss a coin
int main()
{
int maxTails = 0;
int maxHeads = 0;
int currentTotalTails = 0;
int currentTotalHeads = 0;
srand(time(NULL));
for (int i = 0; i < LOOP; ++i) //tosses a coin LOOP times
{
if (rand() % 2 == 0)// heads
{
currentTotalHeads++;
currentTotalTails = 0;
if (currentTotalHeads > maxHeads)
maxHeads = currentTotalHeads;
}
else // tails
{
currentTotalTails++;
currentTotalHeads = 0;
if (currentTotalTails > maxTails)
maxTails = currentTotalTails;
}
}
std::cout << "Max Heads in a row: " << maxHeads << std::endl;
std::cout << "Max Tails in a row: " << maxTails << std::endl;
system("pause");
return 0;
}
答案 1 :(得分:0)
这可能是您的随机数生成的问题。由于所有随机数生成器都使用时钟和播种后经过的时间,因此如果代码的执行每个循环花费的时间大致相同,那么模式就会出现。这可以解释为什么它只出现在15中。我在我的介绍课上制作了一个石头剪刀游戏,我可以以90%的速度持续赢得(不是一个非常公平的游戏)。
尝试改变您的控制流程。有一个随机数生成器,可以控制发生的迭代次数
loopCnt = 0;
while(loopCnt < LOOP)
{
nextLoops = rand() % (LOOP - loopCnt);
for(int i = 0; i < nextLoops; ++i)
{
// COUNT IN A ROW.
++loopCnt;
}
}
这应该会改变你的模式不会出现的流量。