std::string generateExpression() { // 随机生成带括号的加减乘除表达式的函数 int num1 = generateRandomNumber(1, 20); int num2 = generateRandomNumber(1, 20); int num3 = generateRandomNumber(1, 20); int op1 = generateRandomNumber(1, 4); int op2 = generateRandomNumber(1, 4); char oper1, oper2; switch (op1) { case 1: oper1 = '+'; break; case 2: oper1 = '-'; break; case 3: oper1 = '*'; break; case 4: oper1 = '/'; break; } switch (op2) { case 1: oper2 = '+'; break; case 2: oper2 = '-'; break; case 3: oper2 = '*'; break; case 4: oper2 = '/'; break; } // 在计算式中添加括号 std::string expression = "(" + std::to_string(num1) + " " + oper1 + " " + std::to_string(num2) + ") " + oper2 + " " + std::to_string(num3); return expression; }
这是随机生成计算式的代码
double evaluateExpression(const std::string& expression) { // 计算表达式结果的函数 int num1, num2, num3; char oper1, oper2; sscanf(expression.c_str(), "(%d %c %d) %c %d", &num1, &oper1, &num2, &oper2, &num3); double result = 0; switch (oper1) { case '+': result = num1 + num2; break; case '-': result = num1 - num2; break; case '*': result = num1 * num2; break; case '/': result = static_cast<double>(num1) / num2; break; } switch (oper2) { case '+': result += num3; break; case '-': result -= num3; break; case '*': result *= num3; break; case '/': result /= num3; break; } return result; }
这是将生成的代码进行计算
再这些代码中,能够实现带有括号的三个数的运算,能够准确算出
标签:case,num1,幼儿,break,result,算数,oper1,oper2 From: https://www.cnblogs.com/zjq164/p/17499238.html