C++ 实现简单的算术表达式解释器
以下是一个简单的 C++ 解释器示例,可以解释一些基本的算术表达式:
#include <iostream>
#include <string>
#include <stack>
#include <sstream>
using namespace std;
int interpret(string expression) {
stack<int> stack;
string token;
istringstream iss(expression);
while (iss >> token) {
if (token == '+') {
int operand2 = stack.top();
stack.pop();
int operand1 = stack.top();
stack.pop();
stack.push(operand1 + operand2);
} else if (token == '-') {
int operand2 = stack.top();
stack.pop();
int operand1 = stack.top();
stack.pop();
stack.push(operand1 - operand2);
} else if (token == '*') {
int operand2 = stack.top();
stack.pop();
int operand1 = stack.top();
stack.pop();
stack.push(operand1 * operand2);
} else if (token == '/') {
int operand2 = stack.top();
stack.pop();
int operand1 = stack.top();
stack.pop();
stack.push(operand1 / operand2);
} else {
stack.push(stoi(token));
}
}
return stack.top();
}
int main() {
string expression;
cout << 'Enter an arithmetic expression: ';
getline(cin, expression);
int result = interpret(expression);
cout << 'Result: ' << result << endl;
return 0;
}
这个简易解释器可以接受用户输入的算术表达式,并计算出结果。它使用堆栈数据结构来存储和操作操作数和运算符。支持加法 (+)、减法 (-)、乘法 (*) 和除法 (/) 运算。用户可以输入多个操作数和运算符,以空格分隔。解释器会按照运算符的优先级进行计算,并输出最终结果。
原文地址: https://www.cveoy.top/t/topic/bIPW 著作权归作者所有。请勿转载和采集!