#define _CRT_SECURE_NO_WARNINGS #include#include #include void print_menu() { puts("************************"); puts("**** 1. Start Game ****"); puts("**** 0. Exit ****"); puts("************************"); } int main() { srand((unsigned)time(NULL)); // 全程只呼叫一次! int choice = 1; puts("Welcome to Guess Number Game!"); while (choice) { print_menu(); printf("Enter choice: "); if (scanf("%d", &choice) != 1) { while (getchar() != '\n'); // 清理非數字輸入 puts("Invalid input!"); continue; } switch (choice) { case 1: { int target = rand() % 101; int guess; puts("Guess a number (0-100):"); while (1) { printf("> "); if (scanf("%d", &guess) != 1) { while (getchar() != '\n'); puts("Please enter a number!"); 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 option!"); } } return 0; }
| 原始問題 | 改進方案 |
|---|---|
| `srand` 在迴圈中重複呼叫 | 移至 `main` 開頭,僅呼叫一次 |
| 無輸入驗證,`scanf` 失敗導致無限迴圈 | 檢查 `scanf` 回傳值,失敗時清空緩衝區 |
| 魔術數字分散 | 可定義 `MAX_NUM 100` 常數 |
| 單一檔案所有邏輯 | 拆分為 `menu.c/h`、`game.c/h`、`random.c/h` |
猜數字遊戲雖簡單,卻涵蓋了 C 語言**標準庫使用(`