經典教學案例:編寫程式隨機生成 1-10 兩數乘法題,學生輸入答案,程式判斷正誤並給予反饋,循環出題直到結束。本文提供完整 C 語言實現,涵蓋隨機數生成、輸入驗證、循環控制、統計功能,適合初學者鞏固 `while`/`do-while`、`if-else`、`scanf` 返回值判斷等核心控制結構。
#include
#include
#include
int main() {
srand((unsigned)time(NULL)); // 種子初始化,僅一次
int correctCount = 0;
int totalCount = 0;
const int TARGET_CORRECT = 10; // 答對 10 題結束
printf("=== 小學生乘法練習系統 ===\n");
printf("請輸入答案,輸入 -1 可隨時退出\n\n");
while (correctCount < TARGET_CORRECT) {
int a = rand() % 10 + 1; // 1-10
int b = rand() % 10 + 1;
int answer;
printf("%d * %d = ", a, b);
// 輸入驗證:處理非數字輸入、EOF
if (scanf("%d", &answer) != 1) {
printf("輸入無效,請輸入整數。\n");
// 清空輸入緩衝區
int c;
while ((c = getchar()) != '\n' && c != EOF);
continue;
}
if (answer == -1) {
printf("主動退出練習。\n");
break;
}
totalCount++;
if (answer == a * b) {
printf("Right!\n");
correctCount++;
} else {
printf("Wrong! 正確答案是 %d\n", a * b);
}
printf("--- 當前正確率: %d/%d (%.1f%%) ---\n\n",
correctCount, totalCount,
totalCount > 0 ? (100.0 * correctCount / totalCount) : 0);
}
printf("\n=== 練習結束 ===\n");
printf("總題數: %d\n", totalCount);
printf("正確數: %d\n", correctCount);
printf("最終正確率: %.1f%%\n", totalCount > 0 ? (100.0 * correctCount / totalCount) : 0);
return 0;
}
| 知識點 | 代碼體現 | 易錯點提示 |
|---|---|---|
| 隨機數 | `srand(time(NULL))` + `rand()%10+1` | `srand` 僅調用一次!放循環內會導致同秒內生成相同序列 |
| 輸入驗證 | `scanf("%d", &ans) != 1` 判斷失敗 | 失敗時緩衝區殘留非法字符,**必須清空** (getchar 循環),否則無限循環 |
| 循環控制 | `while (correctCount < TARGET)` | 條件變量在循環內更新,避免死循環 |
| 條件分支 | `if-else` 判斷正誤、退出 | 注意 `else if` 順序,優先處理退出碼 |
| 格式化輸出 | `printf` 佔位符 `%d` `%.1f%%` | `%%` 輸出百分號,浮點數精度控制 |
=== 小學生乘法練習系統 ===
請輸入答案,輸入 -1 可隨時退出
5 * 2 = 10
Right!
--- 當前正確率: 1/1 (100.0%) ---
9 * 4 = 36
Right!
--- 當前正確率: 2/2 (100.0%) ---
6 * 4 = 24
Right!
...
9 * 3 = 28
Wrong! 正確答案是 27
--- 當前正確率: 8/10 (80.0%) ---
2 * 8 = 16
Right!
...
10 * 10 = 100
Right!
=== 練習結束 ===
總題數: 13
正確數: 10
最終正確率: 76.9%
這個小程式雖簡單,卻完整串聯了「輸入→處理→輸出→循環」的程式設計核心閉環。建議初學者**手敲三遍**,嘗試修改題型、添加統計、優化輸入體驗,在改錯中真正內化控制結構的靈活運用。