在多个实例上多次生成0和1的随机值

时间:2016-10-25 22:30:06

标签: c

我不明白为什么x场比赛的输出结果与每轮比赛相同的掷硬币总数和头尾数相同

int random_var(void);

int main(void)
{
    int numHEAD = 0, numTAIL = 0, cointoss, numGAME, round = 1;

    printf("Enter the number of games you wish to play: ");
    scanf("%d", &numGAME);

    srand((unsigned) time(NULL));
    while (round <= numGAME)
    {

        while (numHEAD < 20 || numTAIL < 20)
        {
            cointoss = random_var();
            printf("%d\n", cointoss);
            if (cointoss == HEAD)
                numHEAD++;
            if (cointoss == TAIL)
                numTAIL++;
    }

    if (numHEAD == 20)
        printf("Game   Tries/Game     Event\n%-4d   %d             %d HEADs\n", round, numHEAD + numTAIL, numHEAD);
    if (numTAIL == 20)
        printf("Game   Tries/Game     Event\n%-4d   %d             %d TAILs\n", round, numHEAD + numTAIL, numTAIL);

    round++;
    }


return 0;
}


int random_var(void)
{
    return rand() % 2;
}

1 个答案:

答案 0 :(得分:3)

你永远不会重置numHEADnumTAIL所以一旦玩了第一场比赛,它就会为剩下的比赛重复那场比赛。这样做:

 while (round <= numGAME) {
     int numHEAD = 0, numTAIL = 0;
     ...