
同樣的,若是利用 while 迴圈做固定次數的應用,加入控制變數即可,如下

我們將建立擲骰子的亂數表當作例子,把原本的 for 迴圈用 while 改寫,如下
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 | #include <stdio.h> #include <stdlib.h> #include <time.h> int main( void ) { int points1[10]; // 第一組骰子表格 int points2[10]; // 第二組骰子表格 int temp; // 暫存變數 int i; // 迴圈用變數 srand ( time (NULL)); // 利用迴圈取得骰子點數,然後存入表格 i = 0; while (i < 10) { temp = rand () % 6; if (temp == 0) { temp = 6; } points1[i] = temp; temp = rand () % 6; if (temp == 0) { temp = 6; } points2[i] = temp; i++; } // 印出表格內的值 printf ( "第一個骰子點數表為 " ); i = 0; while (i < 10) { printf ( "%d " , points1[i]); i++; } printf ( "\n" ); printf ( "第二個骰子點數表為 " ); i = 0; while (i < 10) { printf ( "%d " , points2[i]); i++; } printf ( "\n" ); return 0; } /* 《程式語言教學誌》的範例程式 檔名:dice4.c 功能:簡單的擲骰子遊戲 作者:張凱慶 時間:西元2010年7月 */ |
編譯執行的結果會是一樣的。
while 迴圈跟 for 迴圈為 C 語言中最常用的兩種迴圈,雖然互相可以替代,但是依特性用處各異。所以接觸久了,多看別人寫的程式,自然就會習慣哪個用在哪裡囉!
問題與討論
- 想一想,什麼情況適合用前測試的 while 迴圈?
- 為什麼說 while 迴圈常用於不固定次數的應用?
沒有留言:
張貼留言