用c++实现一个程序:
任意生成30道两位数四则运算题目,要求:减法输出结果不可以出现负数,除法输出结果不能有小数,乘法输出结果位数不可超过999.
代码实现
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int generateNumber(int min, int max) {
return min + rand() % (max - min + 1);
}
char generateOperator() {
char operators[] = {'+', '-', '*', '/'};
int index = rand() % 4;
return operators[index];
}
bool checkSubtraction(int operand1, int operand2) {
return operand1 >= operand2;
}
bool checkMultiplication(int operand1, int operand2) {
return operand1 * operand2 <= 99;
}
bool checkDivision(int operand1, int operand2) {
return operand1 % operand2 == 0;
}
int main() {
srand(time(0));
int correctCount = 0;
int wrongCount = 0;
for (int i = 0; i < 30; i++) {
int operand1 = generateNumber(10, 99);
int operand2 = generateNumber(10, 99);
char op = generateOperator();
int result = 0;
string operatorStr;
switch (op) {
case '+':
result = operand1 + operand2;
operatorStr = "+";
break;
case '-':
if (!checkSubtraction(operand1, operand2)) {
i--;
continue;
}
result = operand1 - operand2;
operatorStr = "-";
break;
case '*':
if (!checkMultiplication(operand1, operand2)) {
i--;
continue;
}
result = operand1 * operand2;
operatorStr = "*";
break;
case '/':
if (!checkDivision(operand1, operand2)) {
i--;
continue;
}
result = operand1 / operand2;
operatorStr = "/";
break;
}
int answer;
cout << "题目" << i+1 << ": " << operand1 << " " << operatorStr << " " << operand2 << " = ";
cin >> answer;
if (answer == result) {
cout << "回答正确!" << endl;
correctCount++;
} else {
cout << "回答错误!" << endl;
wrongCount++;
}
}
cout << "回答正确的题目数量: " << correctCount << endl;
cout << "回答错误的题目数量: " << wrongCount << endl;
return 0;
}
//这个代码还需改进,求大佬指点迷津。
标签:operand1,cout,9.18,operand2,int,result,return,随笔 From: https://www.cnblogs.com/my0326/p/17713171.html