假設使用者一開始有 100 個籌碼,每玩一次壓 5 個,我們來模擬看看實際玩遊戲使用者籌碼實際的變化吧!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | #include <stdio.h> #include <stdlib.h> #include <time.h> #define SIZE 1000 #define ORIGIN 100 int main( void ) { int points1[SIZE]; // 第一組骰子表格 int points2[SIZE]; // 第二組骰子表格 int temp; // 暫存變數 int i; // 迴圈用變數 int jeton = ORIGIN; // 玩家的籌碼 int n = 5; // 儲存籌碼值 int result[SIZE]; // 儲存玩家的籌碼變化 srand ( time (NULL)); // 建立兩組骰子的亂數表 for (i = 0; i < SIZE; i++) { temp = rand () % 6; if (temp == 0) { temp = 6; } points1[i] = temp; temp = rand () % 6; if (temp == 0) { temp = 6; } points2[i] = temp; } // 假設玩 SIZE 次,計算使用者手中籌碼的變化 for (i = 0; i < SIZE; i++) { if (points1[i] == points2[i]) { result[i] = jeton; } if (points1[i] > points2[i]) { jeton += n; result[i] = jeton; } if (points1[i] < points2[i]) { jeton -= n; result[i] = jeton; } } // 印出 300 次的使用者現有籌碼 for (i = 1; i < 301; i++) { printf ( "%3d " , result[i]); if (i % 15 == 0) { printf ( "\n" ); } } printf ( "\n" ); return 0; } /* 《程式語言教學誌》的範例程式 檔名:dice6.c 功能:簡單的擲骰子遊戲 作者:張凱慶 時間:西元2010年7月 */ |
我們用另一個整數陣列 result[SIZE] 儲存使用者籌碼的變化,另外我們定義另一個常數 ORIGIN 標示最初使用者的籌碼值。
第 35 行到第 50 行,我們利用 for 迴圈將每一次籌碼的變化存進 result 中
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | // 假設玩 SIZE 次,計算使用者手中籌碼的變化 for (i = 0; i < SIZE; i++) { if (points1[i] == points2[i]) { result[i] = jeton; } if (points1[i] > points2[i]) { jeton += n; result[i] = jeton; } if (points1[i] < points2[i]) { jeton -= n; result[i] = jeton; } } |
第 52 行到第 60 行,我們印出前 300 次的籌碼變化
35 36 37 38 39 40 41 42 43 | // 印出 300 次的使用者現有籌碼 for (i = 1; i < 301; i++) { printf ( "%3d " , result[i]); if (i % 15 == 0) { printf ( "\n" ); } } printf ( "\n" ); |
因此,就會把前 300 次籌碼變化的情形全部印出來,好了,直接編譯執行看看囉!

問題與討論
- 為什麼只印出前 300 次的結果變化?
- 想一想,能不能多跑幾次,然後記錄每一次的輸贏結果?
沒有留言:
張貼留言