程序未按预期返回结果。可能滥用“bool”?

时间:2013-09-19 21:04:32

标签: c random srand

我是编程新手,我不得不开发一个可以模拟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;
}

2 个答案:

答案 0 :(得分:2)

您已过度播种,请移除srand()中对diceRoll的来电,您应该没事(这会忽略bias due to modulo usage)。

答案 1 :(得分:0)

仅在main()中播种(而不是在循环中)并且不会在diceRoll(a)函数中播种。

我按照你的方式跑了,得到了house = 2, player = 9998

删除srand((unsigned)time(null));中的diceroll(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;
}