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

C語言數學練習生成器完整實作:隨機出題、計分、等級評定

     編輯:C 語言問答

需求分析

  • 隨機產生 10 道加減法題目(運算元 0~50,結果 0~50)。
  • 每題最多答 3 次,分數遞減:10/7/5 分。
  • 不重複出題。
  • 最終依總分輸出等級:SMART/GOOD/OK/PASS/TRY AGAIN。

核心資料結構

#define MAX_Q 10
#define MAX_TRIES 3
int scores[MAX_TRIES] = {10, 7, 5};
char questions[MAX_Q][30]; // 儲存題目字串供去重比對

關鍵演算法:不重複隨機出題


int a, b, op, ans;
char buf[30];
do {
    a = rand() % 51;
    b = rand() % 51;
    op = rand() % 2; // 0:+, 1:-
    ans = (op == 0) ? a + b : a - b;
    if (ans < 0 || ans > 50) continue; // 結果範圍過濾
    sprintf(buf, "%d %c %d = ", a, op==0?'+':'-', b);
    // 檢查是否重複
    int dup = 0;
    for (int i = 0; i < q_count; i++)
        if (strcmp(questions[i], buf) == 0) { dup = 1; break; }
    if (!dup) break;
} while (1);
strcpy(questions[q_count], buf);

回答與計分邏輯


printf("%s", buf);
for (int try = 0; try < MAX_TRIES; try++) {
    int input;
    scanf("%d", &input);
    if (input == ans) {
        total += scores[try];
        printf("正確!\n");
        break;
    } else if (try < MAX_TRIES - 1) {
        printf("錯誤,再試一次:");
    }
}

完整主程式架構


int main() {
    srand((unsigned)time(NULL));
    int total = 0, q_count = 0;
    while (q_count < MAX_Q) {
        // 生成題目 (同上)
        // 回答計分 (同上)
        q_count++;
    }
    // 輸出等級
    printf("\n總分: %d\n", total);
    if (total >= 90) puts("SMART");
    else if (total >= 80) puts("GOOD");
    else if (total >= 70) puts("OK");
    else if (total >= 60) puts("PASS");
    else puts("TRY AGAIN");
    return 0;
}

編譯執行提示

  • 需連結數學庫:gcc math_game.c -o math_game -lm (部分平台 rand/srand 在 stdlib.h 無需 -lm)。
  • Windows conio.h 非標準,建議移除 getch() 或用標準 getchar()。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved