生成一段算符优先分析程序
时间: 2023-11-14 14:05:12 浏览: 125
以下是一个简单的算符优先分析程序:
```c++
#include <iostream>
#include <stack>
#include <string>
using namespace std;
// 定义运算符优先级
int precedence(char op) {
if (op == '+' || op == '-') {
return 1;
} else if (op == '*' || op == '/') {
return 2;
} else if (op == '^') {
return 3;
} else {
return 0;
}
}
// 执行算符优先分析
void operatorPrecedenceAnalysis(string expression) {
// 定义符号栈和数值栈
stack<char> operatorStack;
stack<int> valueStack;
// 遍历表达式
for (int i = 0; i < expression.length(); i++) {
char currentChar = expression[i];
// 如果是数字,将其转换为 int 类型并压入数值栈
if (isdigit(currentChar)) {
int value = currentChar - '0';
while (i+1 < expression.length() && isdigit(expression[i+1])) {
value = value * 10 + (expression[i+1] - '0');
i++;
}
valueStack.push(value);
}
// 如果是运算符
else if (currentChar == '+' || currentChar == '-' || currentChar == '*' || currentChar == '/' || currentChar == '^') {
// 将当前运算符的优先级与符号栈顶的运算符的优先级进行比较
while (!operatorStack.empty() && precedence(operatorStack.top()) >= precedence(currentChar)) {
// 取出符号栈顶的运算符和数值栈顶的两个数进行运算
char op = operatorStack.top();
operatorStack.pop();
int rightValue = valueStack.top();
valueStack.pop();
int leftValue = valueStack.top();
valueStack.pop();
int result = 0;
if (op == '+') {
result = leftValue + rightValue;
} else if (op == '-') {
result = leftValue - rightValue;
} else if (op == '*') {
result = leftValue * rightValue;
} else if (op == '/') {
result = leftValue / rightValue;
} else if (op == '^') {
result = pow(leftValue, rightValue);
}
// 将运算结果压入数值栈
valueStack.push(result);
}
// 将当前运算符压入符号栈
operatorStack.push(currentChar);
}
}
// 执行剩余的运算
while (!operatorStack.empty()) {
char op = operatorStack.top();
operatorStack.pop();
int rightValue = valueStack.top();
valueStack.pop();
int leftValue = valueStack.top();
valueStack.pop();
int result = 0;
if (op == '+') {
result = leftValue + rightValue;
} else if (op == '-') {
result = leftValue - rightValue;
} else if (op == '*') {
result = leftValue * rightValue;
} else if (op == '/') {
result = leftValue / rightValue;
} else if (op == '^') {
result = pow(leftValue, rightValue);
}
// 将运算结果压入数值栈
valueStack.push(result);
}
// 输出最终结果
cout << "Result: " << valueStack.top() << endl;
}
int main() {
string expression = "3+4*2/(1-5)^2^3";
operatorPrecedenceAnalysis(expression);
return 0;
}
```
该程序可以对算术表达式进行算符优先分析,并计算出表达式的值。运行结果如下:
```
Result: 3
```
阅读全文