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

C 語言控制台小遊戲:猜數字帶菜單循環

     編輯:關於C

功能完整代碼

#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、隨機數、循環結構。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved