#include#include #include void menu() { puts("********** 1. Start **********"); puts("********** 0. Exit **********"); } int main() { srand((unsigned)time(NULL)); // 單次呼叫 int choice = 1; puts("Welcome to Guess Number Game!"); while (choice) { menu(); printf("Choice: "); if (scanf("%d", &choice) != 1) { while(getchar()!='\n'); continue; } switch (choice) { case 1: { int target = rand() % 101; int guess; while (1) { printf("Guess (0-100): "); if (scanf("%d", &guess) != 1) { while(getchar()!='\n'); continue; } if (guess > target) puts("Too large!"); else if (guess < target) puts("Too small!"); else { puts("Correct!"); break; } } break; } case 0: puts("Goodbye!"); break; default: puts("Invalid!"); } } return 0; }
| 錯誤寫法 | 後果 | 正確寫法 |
|---|---|---|
| `srand` 在 `while` 內 | 同秒內多局遊戲答案相同 | `main` 開頭單次呼叫 |
| `rand() % 100` | 範圍 0~99,非 0~100 | `rand() % 101` |
| 無 `scanf` 回傳檢查 | 輸入字母導致無限迴圈 | `if(scanf(...)!=1) clear_buf()` |
| 魔術數字分散 | 維護困難 | `#define MAX 100` |
猜數字遊戲是 C 語言入門的「Hello World」進階版。掌握**隨機數正確用法、輸入驗證模式、選單狀態機架構**,即可舉一反三開發各類文字互動程式。本文提供的標準實作模式可直接作為專案模板擴展。