經典賭場遊戲 Craps(街頭骰子)規則簡單:擲兩顆骰子,首擲和為 7/11 莊家贏,2/3/12 莊家輸(Craps out),其他點數進入「點數階段」。本文實現首擲勝率統計模擬,10,000 次獨立試驗,驗證理論概率(勝 2/9 ≈ 0.2222,負 1/9 ≈ 0.1111)。
#include
#include
#include
#define ROLLS 10000
void diceRoll(int *d1, int *d2) {
*d1 = 1 + rand() % 6;
*d2 = 1 + rand() % 6;
}
int main() {
unsigned int seed;
printf("Enter an integer seed value: ");
if (scanf("%u", &seed) != 1) return 1;
srand(seed);
int wins = 0, losses = 0;
for (int i = 0; i < ROLLS; i++) {
int d1, d2;
diceRoll(&d1, &d2);
int sum = d1 + d2;
if (sum == 7 || sum == 11) wins++;
else if (sum == 2 || sum == 3 || sum == 12) losses++;
}
printf("Number of wins: %d\n", wins);
printf("Probability of winning: %.4f\n", (double)wins / ROLLS);
printf("Number of losses: %d\n", losses);
printf("Probability of losing: %.4f\n", (double)losses / ROLLS);
return 0;
}
| 項目 | 說明 |
|---|---|
| 隨機種子 | 用戶輸入 unsigned int,srand() 初始化,保證可復現 |
| 骰子函數 | diceRoll 透過指標返回兩顆骰子值,符合題目要求 |
| 均勻分布 | 1 + rand() % 6 產生 1~6(假設 RAND_MAX 足大,偏差可忽略) |
| 統計精度 | 10,000 次試驗,標準誤差 ~0.004,足以觀測收斂趨勢 |
| 輸出格式 | 符合題目範例:勝/負次數與機率保留 4 位小數 |