完整代碼
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void game() {
static int seeded = 0;
if (!seeded) { srand((unsigned)time(NULL)); seeded = 1; }
int target = rand() % 100;
int guess;
do {
printf("請輸入猜測: ");
scanf("%d", &guess);
if (guess > target) puts("太大了");
else if (guess < target) puts("太小了");
else { puts("猜中了!"); break; }
} while (1);
}
void menu() {
puts("************************");
puts("**** 1.開始遊戲 ********");
puts("**** 0.退出遊戲 ********");
puts("************************");
}
int main() {
int choice = 1;
while (choice) {
menu();
printf("請選擇: ");
scanf("%d", &choice);
if (choice == 1) game();
}
return 0;
}
工程亮點
static seeded 確保 srand 全程只調用一次,避免同秒重複序列;
do-while 保證至少猜一次,邏輯更自然;
- 菜單、遊戲邏輯分離,單一職責;
- 輸入建議加檢查
scanf 返回值,防非數字輸入死循環。