包含括号, 可获取赋值表达式桌面计算器代码实现c++
时间: 2023-12-02 10:06:43 浏览: 24
以下是一个简单的桌面计算器代码实现(C++):
```cpp
#include <iostream>
#include <stack>
using namespace std;
int priority(char op) {
if (op == '+' || op == '-') return 1;
if (op == '*' || op == '/') return 2;
return 0;
}
double calculate(double a, double b, char op) {
if (op == '+') return a + b;
if (op == '-') return a - b;
if (op == '*') return a * b;
if (op == '/') return a / b;
return 0;
}
double evaluate(string expression) {
stack<double> operands;
stack<char> operators;
for (int i = 0; i < expression.length(); i++) {
if (isdigit(expression[i])) {
double operand = 0;
while (i < expression.length() && isdigit(expression[i])) {
operand = operand * 10 + (expression[i] - '0');
i++;
}
i--;
operands.push(operand);
}
else if (expression[i] == '(') {
operators.push(expression[i]);
}
else if (expression[i] == ')') {
while (operators.top() != '(') {
double b = operands.top();
operands.pop();
double a = operands.top();
operands.pop();
char op = operators.top();
operators.pop();
operands.push(calculate(a, b, op));
}
operators.pop(); // pop '('
}
else if (expression[i] == '+' || expression[i] == '-' || expression[i] == '*' || expression[i] == '/') {
while (!operators.empty() && priority(operators.top()) >= priority(expression[i])) {
double b = operands.top();
operands.pop();
double a = operands.top();
operands.pop();
char op = operators.top();
operators.pop();
operands.push(calculate(a, b, op));
}
operators.push(expression[i]);
}
}
while (!operators.empty()) {
double b = operands.top();
operands.pop();
double a = operands.top();
operands.pop();
char op = operators.top();
operators.pop();
operands.push(calculate(a, b, op));
}
return operands.top();
}
int main() {
string expression = "(5+3)*2-4/2";
double result = evaluate(expression);
cout << expression << " = " << result << endl;
return 0;
}
```
这个实现使用了两个栈:一个栈用于存储操作数,另一个栈用于存储操作符。在处理表达式时,我们扫描表达式并处理以下三种情况:
1. 如果当前字符是数字,则将其作为操作数压入操作数栈中。
2. 如果当前字符是左括号,则将其压入操作符栈中。
3. 如果当前字符是右括号,则从操作符栈中弹出操作符和操作数栈中的两个操作数,计算它们的值,并将结果压入操作数栈中,直到遇到左括号为止。
4. 如果当前字符是操作符,则从操作符栈中弹出操作符和操作数栈中的两个操作数,计算它们的值,并将结果压入操作数栈中,直到操作符栈为空或者栈顶操作符的优先级小于当前操作符的优先级为止。然后将当前操作符压入操作符栈中。
最后,当我们处理完整个表达式后,我们从操作符栈中弹出操作符和操作数栈中的两个操作数,计算它们的值,并将结果压入操作数栈中,直到操作数栈中只剩下一个元素为止。这个元素就是表达式的值。