#include <iostream>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <limits>
// 函数原型声明
int getRandomNumber(int min, int max);
int main() {
int n;
std::cout << "请输入题目的数量: " << std::endl;
std::cin >> n;
// 初始化随机数生成器
srand(static_cast<unsigned int>(time(0)));
// 创建一个ofstream对象用于写入问题和答案
std::ofstream outQuestionFile("question.txt");
std::ofstream outAnswerFile("answer.txt");
if (!outQuestionFile || !outAnswerFile) {
// 如果文件打开失败,输出错误信息
std::cerr << "Unable to open file for writing." << std::endl;
return 1;
}
int cnt = 0;
while (cnt < n) {
int num1, num2;
char op;
double result;
do {
num1 = getRandomNumber(1, 100);
num2 = getRandomNumber(1, 100);
int opCode = rand() % 4;
switch (opCode) {
case 0:
op = '+';
result = num1 + num2;
break;
case 1:
op = '-';
result = num1 - num2;
break;
case 2:
op = '*';
result = num1 * num2;
break;
case 3:
op = '/';
result = num1 != 0 ? static_cast<double>(num1) / num2 : std::numeric_limits<double>::max(); // 防止除以0
break;
default:
op = '+';
result = num1 + num2;
}
} while (result >= 100 || (op == '/' && num1 % num2 != 0) || (op == '/' && num2 == 0));
// 将问题和答案写入文件
outQuestionFile << num1 << ' ' << op << ' ' << num2 << " = \n";
outAnswerFile << num1 << ' ' << op << ' ' << num2 << " = " << result << std::endl;
cnt++;
}
// 关闭文件
outQuestionFile.close();
outAnswerFile.close();
std::cout << "题目和答案已分别写入 question.txt 和 answer.txt 文件中。" << std::endl;
return 0;
}
// 生成指定范围内的随机数
int getRandomNumber(int min, int max) {
return rand() % (max - min + 1) + min;
}
学号:2252427
标签:std,结对,ofstream,num1,num2,int,编程,include From: https://www.cnblogs.com/Decoi/p/18156222