經典控制台猜數字遊戲:程式隨機生成 1~100 的整數,玩家有 5 次機會猜測,每次提示「偏大/偏小」,猜中或用盡機會結束,支援重玩。
#include
#include
#include
#include
int main() {
int secret, guess, attempts = 5;
char answer;
srand((unsigned)time(NULL)); // 種子初始化
do {
secret = rand() % 100 + 1; // 1~100
attempts = 5;
printf("\n=== 猜數字遊戲 ===\n");
printf("你有 5 次機會,請輸入 1-100 之間的數字!\n");
while (attempts > 0) {
printf("請輸入猜測 (剩餘 %d 次): ", attempts);
if (scanf("%d", &guess) != 1) {
printf("輸入無效,請輸入數字!\n");
while (getchar() != '\n'); // 清空緩衝區
continue;
}
attempts--;
if (guess == secret) {
printf("恭喜!你用了 %d 次猜中了!\n", 5 - attempts);
break;
} else if (guess > secret) {
printf("偏大了!");
} else {
printf("偏小了!");
}
if (attempts > 0) printf(" 還有 %d 次機會。\n", attempts);
}
if (attempts == 0 && guess != secret)
printf("\n遊戲結束,正確答案是 %d。\n", secret);
printf("再玩一局?(y/n): ");
scanf(" %c", &answer); // 空格跳過換行符
} while (tolower(answer) == 'y');
printf("謝謝遊玩,再見!\n");
return 0;
}
srand(time(NULL)) 種子 + rand() % 100 + 1 範圍控制scanf 返回值,清理緩衝區防止死循環tolower() 處理 'y'/'Y'這個小專案涵蓋了輸入輸出、隨機數、流程控制、防錯輸入等 C 語言核心基礎,極適合初學者練手。