| 問題 | 影響 | 修正 |
|---|---|---|
| 缺少 ` | `srand`/`rand`/`time` 隱性宣告警告 | 加入標頭檔 |
| `srand` 在迴圈內 | 同秒內重複遊戲答案相同 | 移至 `main` 開頭 |
| 無輸入驗證 | 非數字輸入導致無限迴圈 | 檢查 `scanf` 回傳值 |
| 邏輯順序:`if(ch==n)` 放在最後 | 猜中時仍先印「太大/太小」 | 優先判斷相等 |
#include#include #include void menu() { puts("***************************"); puts("**** 1. Start *************"); puts("**** 0. Exit *************"); puts("***************************"); } int main() { srand((unsigned)time(NULL)); // 單次! int choice = 1; puts("**** Welcome to Guess 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("Correct!"); break; } else if (guess > target) puts("Too large!"); else puts("Too small!"); } break; } case 0: puts("Bye!"); break; default: puts("Invalid!"); } } return 0; }
簡易猜數字遊戲雖小,卻暴露初學者最常見的四大錯誤:**標頭檔遺漏、隨機數種子誤用、輸入驗證缺失、判斷順序不當**。逐一修正後,程式碼即具備基本健壯性,可作為進階功能擴展基底。