編寫一個控制台程式,隨機生成 10 以內的加減乘除題目,供使用者練習。需包含:題目生成、輸入判斷、統計正確率、多輪練習等功能。
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
srand(static_cast<unsigned>(time(0)));
int correct = 0, total = 0;
char op;
int a, b, ans, userAns;
bool continueGame = true;
cout << "=== 10 以內四則運算練習 ===" << endl;
while (continueGame) {
a = rand() % 10 + 1; // 1-10
b = rand() % 10 + 1;
int opType = rand() % 4; // 0:+, 1:-, 2:*, 3:/
switch (opType) {
case 0: op = '+'; ans = a + b; break;
case 1: op = '-'; ans = a - b; break; // 可能產生負數,視需求調整
case 2: op = '*'; ans = a * b; break;
case 3:
// 除法確保整除
ans = a;
a = a * b; // 被除數 = 商 * 除數
op = '/';
break;
}
cout << a << " " << op << " " << b << " = ";
if (!(cin >> userAns)) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "輸入無效,請輸入整數。" << endl;
continue;
}
total++;
if (userAns == ans) {
cout << "正確!" << endl;
correct++;
} else {
cout << "錯誤,正確答案是 " << ans << endl;
}
cout << "繼續練習?(y/n): ";
char ch; cin >> ch;
if (ch != 'y' && ch != 'Y') continueGame = false;
}
cout << "總題數: " << total << ", 正確: " << correct
<< ", 正確率: " << (total? 100.0*correct/total : 0) << "%" << endl;
return 0;
}
更完整的專案結構可參考:C++ 簡易數學練習程式。