#include <iostream>
#include <cstdlib>
#include <ctime>
#include <fstream>
using namespace std;
void additionExercise(int n) {
srand(time(0));
int score = 0;
for (int i = 0; i < n; i++) {
int a = rand() % 20 + 1;
int b = rand() % 20 + 1;
cout << a << " + " << b << " = ";
int answer;
cin >> answer;
if (answer == a + b) {
score++;
} else {
cout << "Wrong! The correct answer is " << a + b << endl;
}
}
cout << "Your score: " << score << "/" << n << endl;
}
void subtractionExercise(int n) {
srand(time(0));
int score = 0;
for (int i = 0; i < n; i++) {
int a = rand() % 20 + 1;
int b = rand() % 20 + 1;
if (a < b) swap(a, b);
cout << a << " - " << b << " = ";
int answer;
cin >> answer;
if (answer == a - b) {
score++;
} else {
cout << "Wrong! The correct answer is " << a - b << endl;
}
}
cout << "Your score: " << score << "/" << n << endl;
}
void mixedExercise(int n) {
srand(time(0));
int score = 0;
ofstream file("result.txt");
for (int i = 0; i < n; i++)
{
int a = rand() % 20 + 1;
int b = rand() % 20 + 1;
int c = rand() % 20 + 1;
int op = rand() % 2;
int correctAnswer = (op == 0) ? a + b - c : a - b + c;
cout << a << (op == 0 ? " + " : " - ") << b << (op == 0 ? " - " : " + ") << c << " = ";
int answer;
cin >> answer;
if (answer == correctAnswer) {
score++;
} else {
file << "Wrong answer: " << a << (op == 0 ? " + " : " - ") << b << (op == 0 ? " - " : " + ") << c << " = " << answer << ", correct answer: " << correctAnswer << endl;
}
}
file << "Total: " << n << ", correct: " << score << ", wrong: " << n - score << endl;
file.close();
cout << "Your score: " << score << "/" << n << ", the result has been saved to result.txt" << endl;
}
int main() {
while (true)
{
cout << "1. 加法练习\n2. 减法练习\n3. 混合加减练习\n4. 退出系统\nChoose an option: ";
int option;
cin >> option;
if (option == 4) break;
cout << "Enter the number of questions: ";
int n;
cin >> n;
if (option == 1) additionExercise(n);
else if (option == 2) subtractionExercise(n);
else if (option == 3) mixedExercise(n);
}
return 0;
}