创建了 5 张牌手的模拟,以查看皇家同花顺的概率


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
int main() {
int i, n, j, a, g;
int d=0;
int k=0;
int hold[5];
time_t t;
typedef struct card{
    int suit;
    int value;
} cards;
struct card deck[52];
struct card *hand=malloc(sizeof(char));
n = 5;
void shuffle(cards *array, size_t q) {
    if (q>1) {
        size_t w;
            for (w = 0; w < q - 1; w++)
                {
                    srand(time(NULL));
                    size_t e = w + rand() / (RAND_MAX/ (q - w) + 1);
            cards t = array[e];
            array[e] = array[w];
            array[w] = t;
        }
    }
}
for (g=0; g < 1000000; g++) { // the for loop that controls how many times this simulation occurs
    for (i=0; i<13; i++) {// the following for loops create a deck in order (Ace to King spades, Ace to King clubs, etc)
        deck[i].suit = 1;
        deck[i].value =i+1;
    }
    for (i=13; i < 26; i++) {
        deck[i].suit = 2;
        deck[i].value = i - 12;
    }
    for (i=26; i < 39; i++) {
        deck[i].suit = 3;
        deck[i].value = i - 25;
    }
    for (i=39; i < 52; i++) {
        deck[i].suit = 4;
        deck[i].value = i - 38;
    }

for (i=0; i < 1; i++) // shuffles the deck by randomizing deck[i]{
shuffle(deck, 53);
}
j=51;
for (i=0; i < n; i++) { // deals 5 random cards to a persons hand
    srand(time(NULL));
    k = rand()%j;
    hand[i] = deck[k];
    if (k != j) {
        deck[k] = deck[j];
    }
    j = j-1;
}

for (i=0; i < n; i++) {
    for (j=i+1; j < n; j++) {
        if (hand[i].value > hand[j].value) {
            a = hand[i].value;
            hand[i].value = hand[j].value;
            hand[j].value = a; //organizes the persons hand from smallest to largest card values
        }
    }
}
if (hand[4].value == 13 && hand[3].value == 12 && hand[2].value == 11 && hand[1].value == 10 && hand[0].value == 9) {        if (hand[4].suit == hand[3].suit && hand[4].suit == hand[2].suit && hand[4].suit == hand[1].suit && hand[4].suit == hand[0].suit) {
        d++;
        // since the hand is organized from smallest to largest, if hand[5] is Ace, hand[4] is king etc, then we have a hand that goes from 10 to Ace (smallest to largest, 10 is actually 9 in this case). If all of the suit values are the same, then we have a royal flush. Therefore, increment variable d.
    }
}
}
// do that however many times, and after it is done print d.
printf("%dn", d);
return (0);
}

我的代码的问题在于它总是打印d = 0。我运行了 1000 万次以上的模拟,但 d 仍然是 0。被处理皇家闪光的概率是 1/649,740,所以如果我运行那么多次,我应该会看到一些刷新。我的代码中有错误吗?

任何帮助将不胜感激。

分配的内存不足。 @Weather叶片

与其为hand分配 1 char,代码应该为card分配足够的 5 个。

// struct card *hand = malloc(sizeof(char));
n = 5;
struct card *hand = malloc(sizeof *hand * 5);

。或者干脆

struct card hand[5];

srand(time(NULL)); 进行过多调用的代码。 最好只给srand()打电话一次。 每次调用都会重置随机数规则。 调用srand()将相同的值(相同的时间(将从rand()生成相同的结果序列。 @M.M


main()内部void shuffle(cards *array, size_t q)的本地定义不是标准 C。

--

皇家同花顺的几率是1/649,740。 模拟 1,000,000 手可能是不够的。

最新更新