1

我是编程新手,我必须开发一个可以模拟 10,000 次掷骰子游戏的程序。我得到它来计算房子和玩家的分数,直到我添加了函数“diceRoll”,玩家一次又一次地滚动,直到它匹配第一个滚动或 7(房子获胜)。现在它给出的结果绝对不是随机的(例如房子在 10,000 次中获胜 0 次)。我做错了什么?

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>

bool diceRoll (int a)
{
    srand( (unsigned)time(NULL));
    int n = 0;
    int b = 0;
    while(n < 1) {
        b = rand() % 12;
        if(b == a || b == 6) n++;
    }
    if(b == 6) return false;
    else return true;
}


int main (void)
{
    srand( (unsigned)time(NULL));
    int a, n, house, player, point;
    house = 0;
    player = 0;
    point = 0;

    for(n = 0; n < 10000; n++) {
        a = rand() % 12;
        if(a == 1 || a == 2 || a == 11) {
            house++;
        }
        else if(a == 6 || a == 10) {
            player++;
        }
        else {
            if(diceRoll(a) == true) player++;
            else house++;
        }
    }

    printf("The house has %i points.\n", house);
    printf("The player has %i points.\n", player);
    return 0;
}
4

2 回答 2

2

您已经播种过多,删除了对srand()in的调用diceRoll,您应该没问题(这忽略了由于模使用而导致的偏差)。

于 2013-09-19T21:11:25.653 回答
0

只播种main()(而不是循环),不要在diceRoll(a)函数中播种。

我按照你的方式运行并得到了house = 2, player = 9998.

删除srand((unsigned)time(null));indiceroll(a)回来了:

The house has 5435 points

The player has 4565 points

我想这就是你想要的

bool diceRoll (int a)
{
    int n = 0;
    int b = 0;
    while(n < 1) {
        b = rand() % 12;
        if(b == a || b == 6) n++;
    }
    if(b == 6) return false;
    else return true;
}

int main (void)
{
    srand( (unsigned)time(NULL));
    int a, n, house, player, point;
    house = 0;
    player = 0;
    point = 0;

    for(n = 0; n < 10000; n++) {
        a = rand() % 12;
        if(a == 1 || a == 2 || a == 11) {
            house++;
        }
        else if(a == 6 || a == 10) {
            player++;
        }
        else {
            if(diceRoll(a) == true) player++;
            else house++;
        }
    }

    printf("The house has %i points.\n", house);
    printf("The player has %i points.\n", player);
    return 0;
}
于 2013-09-19T21:11:23.860 回答