功能完整代碼
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void menu() {
puts("**********************");
puts("******* 1.開始 *******");
puts("******* 0.退出 *******");
puts("**********************");
}
void game() {
srand((unsigned)time(NULL));
int target = rand() % 101; // 0-100
int guess;
while (1) {
printf("請猜一個數 (0-100): ");
scanf("%d", &guess);
if (guess > target) puts("猜大了");
else if (guess < target) puts("猜小了");
else { puts("恭喜猜中!"); break; }
}
}
int main() {
int choice = 1;
while (choice) {
menu();
printf("請選擇: ");
scanf("%d", &choice);
if (choice == 1) game();
else if (choice == 0) puts("再見!");
else puts("無效選項");
}
return 0;
}
關鍵點
srand(time(NULL)) 僅調用一次,放在 game() 內每次新遊戲重新播種也可;
rand() % 101 生成 0~100;
- 菜單循環用
while(choice),0 退出;
- 適合初學者練習
switch/if-else、隨機數、循環結構。