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

C 語言猜數字遊戲進階版:模組化設計與 do-while 迴圈結構

     編輯:關於C語言

C 語言猜數字遊戲進階版:模組化設計與 do-while 迴圈結構

完整程式碼

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

void menu() {
    puts("************************");
    puts("**** 1. 開始遊戲 ********");
    puts("**** 0. 退出遊戲 ********");
    puts("************************");
}

void game() {
    int target = rand() % 100 + 1;
    int guess;
    do {
        printf("請輸入猜測 (1-100): ");
        if (scanf("%d", &guess) != 1) {
            puts("輸入錯誤"); while(getchar()!='\n'); continue;
        }
        if (guess > target) puts("太大了");
        else if (guess < target) puts("太小了");
        else { puts("恭喜猜中!"); break; }
    } while (1);
}

int main() {
    srand((unsigned)time(NULL));
    int choice;
    do {
        menu();
        printf("選擇: ");
        if (scanf("%d", &choice) != 1) { while(getchar()!='\n'); continue; }
        switch (choice) {
            case 1: game(); break;
            case 0: puts("再見!"); break;
            default: puts("無效選項");
        }
    } while (choice != 0);
    return 0;
}

設計亮點

  • do-while 確保選單至少顯示一次,符合 UI 直覺。
  • game() 內部 do-while 保證至少猜一次。
  • 輸入錯誤處理:scanf 失敗時清空緩衝區。
  • rand() 種子在 main 只設一次。

與基本版差異

此結構更符合「選單驅動程式」的標準模式。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
特性基本版進階版
主迴圈while(1) + breakdo-while(choice!=0)
遊戲迴圈while(1)do-while(1)
模組化有更清晰