首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C語言猜數字小遊戲:菜單驅動、隨機生成與交互邏輯完整實現

     編輯:關於C語言

C語言猜數字小遊戲:菜單驅動、隨機生成與交互邏輯完整實現

經典入門專案:電腦生成 1~100 隨機數,玩家反覆猜測,提示大/小/正確,支援重玩與退出。

代碼架構

  • menu():打印 ASCII 藝術菜單。
  • game():核心邏輯,srand(time(NULL)) 種子,rand()%100+1 生成目標數,循環讀入猜測並比較。
  • main():循環顯示菜單,switch 分發 1:game() / 2:exit。

完整代碼

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void menu() {
    puts("********************");
    puts("****  猜數字遊戲  ****");
    puts("********************");
    puts("**** 1. 開始遊戲 ****");
    puts("**** 2. 退出遊戲 ****");
    puts("********************");
}

void game() {
    int target = rand() % 100 + 1;
    int guess;
    while (1) {
        printf("請輸入猜測 (1-100):");
        scanf("%d", &guess);
        if (guess == target) { puts("恭喜答對!"); break; }
        else if (guess > target) puts("猜大了!");
        else puts("猜小了!");
    }
}

int main() {
    srand((unsigned)time(NULL));
    int choice;
    while (1) {
        menu();
        printf("請選擇:");
        scanf("%d", &choice);
        if (choice == 1) game();
        else if (choice == 2) { puts("再見!"); break; }
        else puts("無效選項");
    }
    return 0;
}

常見改進

  • 輸入驗證:檢查 scanf 返回值,清理緩衝區防止無限循環。
  • 次數統計/限制:增加變數記錄猜測次數,超過上限判負。
  • 難度選項:調整範圍(1~1000)或提供提示(如「相差 10 以內」)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved