在文件中question.txt逐行存储:
add(23,45)
add(-20,sub(13,10))
add(sub(neg(4),12), muti(doubleMe(2),5))
div(54,add(3,sub(9,3))
将值写入文件answer.txt:
add(23,45)=68
add(20,sub(13,10)) = 23
add(sub(neg(4),12), muti(doubleMe(2),5)) = 4
div(54,add(3,sub(9,3)) = 6
#include <iostream>
#include <fstream>
#include <sstream>
#include <stack>
using namespace std;
int calculate(string expression) {
stack<int> ops;
stack<char> optrs;
int operand1, operand2;
for (int i = 0; i < expression.length(); i++) {
if (expression[i] >= '0' && expression[i] <= '9') {
ops.push(expression[i] - '0'); // 将数字字符转为 int 加入操作数栈
} else if (expression[i] == '(') {
optrs.push(expression[i]); // 将左括号加入操作符栈
} else if (expression[i] == ')') {
while (optrs.top() != '(') { // 将操作符栈中的操作符依次出栈并运算
operand2 = ops.top(); ops.pop();
operand1 = ops.top(); ops.pop();
ops.push(calculate(operand1, operand2, optrs.top()));
optrs.pop();
}
optrs.pop(); // 弹出左括号
} else {
while (!optrs.empty() && precedence(expression[i]) <= precedence(optrs.top())) {
operand2 = ops.top(); ops.pop();
operand1 = ops.top(); ops.pop();
ops.push(calculate(operand1, operand2, optrs.top()));
optrs.pop();
}
optrs.push(expression[i]); // 将当前操作符入栈
}
}
while (!optrs.empty()) {
operand2 = ops.top(); ops.pop();
operand1 = ops.top(); ops.pop();
ops.push(calculate(operand1, operand2, optrs.top()));
optrs.pop();
}
return ops.top();
}
// 运算优先级比较
int precedence(char op) {
if (op == '+' || op == '-') return 1;
if (op == '*' || op == '/') return 2;
return 0;
}
// 进行运算
int calculate(int operand1, int operand2, char optr) {
if (optr == '+') return operand1 + operand2;
if (optr == '-') return operand1 - operand2;
if (optr == '*') return operand1 * operand2;
if (optr == '/') return operand1 / operand2;
}
int main() {
ifstream infile("question.txt");
ofstream outfile("answer.txt");
string expression;
while (getline(infile, expression)) {
int result = calculate(expression);
outfile << expression << "=" << result << endl;
}
}