请用c++利用顺序栈实现表达式的求解
时间: 2024-05-11 16:18:03 浏览: 4
以下是使用顺序栈实现表达式求解的 C++ 代码:
```c++
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int priority(char op) {
if (op == '+' || op == '-') {
return 1;
} else if (op == '*' || op == '/') {
return 2;
} else if (op == '^') {
return 3;
} else {
return -1;
}
}
double calculate(double num1, double num2, char op) {
switch(op) {
case '+':
return num1 + num2;
case '-':
return num1 - num2;
case '*':
return num1 * num2;
case '/':
return num1 / num2;
case '^':
return pow(num1, num2);
}
return 0;
}
double evaluate(string expression) {
stack<double> operand_stack;
stack<char> operator_stack;
for (int i = 0; i < expression.length(); i++) {
char token = expression[i];
if (isdigit(token)) {
double number = 0;
while (i < expression.length() && isdigit(expression[i])) {
number = number * 10 + (expression[i] - '0');
i++;
}
i--;
operand_stack.push(number);
} else if (token == '(') {
operator_stack.push(token);
} else if (token == ')') {
while (operator_stack.top() != '(') {
char op = operator_stack.top();
operator_stack.pop();
double num2 = operand_stack.top();
operand_stack.pop();
double num1 = operand_stack.top();
operand_stack.pop();
operand_stack.push(calculate(num1, num2, op));
}
operator_stack.pop();
} else if (token == '+' || token == '-' || token == '*' || token == '/' || token == '^') {
while (!operator_stack.empty() && priority(operator_stack.top()) >= priority(token)) {
char op = operator_stack.top();
operator_stack.pop();
double num2 = operand_stack.top();
operand_stack.pop();
double num1 = operand_stack.top();
operand_stack.pop();
operand_stack.push(calculate(num1, num2, op));
}
operator_stack.push(token);
}
}
while (!operator_stack.empty()) {
char op = operator_stack.top();
operator_stack.pop();
double num2 = operand_stack.top();
operand_stack.pop();
double num1 = operand_stack.top();
operand_stack.pop();
operand_stack.push(calculate(num1, num2, op));
}
return operand_stack.top();
}
int main() {
string expression;
cout << "请输入表达式(不含空格):" << endl;
cin >> expression;
double result = evaluate(expression);
cout << "表达式的值为:" << result << endl;
return 0;
}
```
在上述代码中,`priority` 函数用于返回运算符的优先级,`calculate` 函数用于计算两个数字的运算结果,`evaluate` 函数用于对表达式进行求值,主函数中调用 `evaluate` 函数并输出结果。