C 語言猜數字遊戲進階版:模組化設計與 do-while 迴圈結構
完整程式碼
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void menu() {
puts("************************");
puts("**** 1. 開始遊戲 ********");
puts("**** 0. 退出遊戲 ********");
puts("************************");
}
void game() {
int target = rand() % 100 + 1;
int guess;
do {
printf("請輸入猜測 (1-100): ");
if (scanf("%d", &guess) != 1) {
puts("輸入錯誤"); while(getchar()!='\n'); continue;
}
if (guess > target) puts("太大了");
else if (guess < target) puts("太小了");
else { puts("恭喜猜中!"); break; }
} while (1);
}
int main() {
srand((unsigned)time(NULL));
int choice;
do {
menu();
printf("選擇: ");
if (scanf("%d", &choice) != 1) { while(getchar()!='\n'); continue; }
switch (choice) {
case 1: game(); break;
case 0: puts("再見!"); break;
default: puts("無效選項");
}
} while (choice != 0);
return 0;
}
設計亮點
do-while 確保選單至少顯示一次,符合 UI 直覺。
game() 內部 do-while 保證至少猜一次。
- 輸入錯誤處理:
scanf 失敗時清空緩衝區。
rand() 種子在 main 只設一次。
與基本版差異