带括号的多位数运算计算器c++代码
时间: 2023-09-01 11:10:28 浏览: 61
以下是一个简单的带括号的多位数运算计算器的C++代码示例:
```c++
#include <iostream>
#include <stack>
#include <cstring>
using namespace std;
// 判断是否是数字
bool isDigit(char c) {
return c >= '0' && c <= '9';
}
// 判断是否是运算符
bool isOperator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/';
}
// 判断运算符优先级
int priority(char c) {
if (c == '+' || c == '-') return 1;
if (c == '*' || c == '/') return 2;
return 0;
}
// 计算表达式
int calculate(int num1, int num2, char op) {
switch (op) {
case '+': return num1 + num2;
case '-': return num1 - num2;
case '*': return num1 * num2;
case '/': return num1 / num2;
default: return 0;
}
}
// 处理括号内的表达式
int processExpression(stack<int>& nums, stack<char>& ops) {
int num2 = nums.top();
nums.pop();
int num1 = nums.top();
nums.pop();
char op = ops.top();
ops.pop();
return calculate(num1, num2, op);
}
// 计算带括号的多位数表达式
int calculateExpression(string expr) {
stack<int> nums;
stack<char> ops;
for (int i = 0; i < expr.length(); i++) {
char c = expr[i];
if (isDigit(c)) {
int num = 0;
while (i < expr.length() && isDigit(expr[i])) {
num = num * 10 + (expr[i] - '0');
i++;
}
i--;
nums.push(num);
} else if (isOperator(c)) {
while (!ops.empty() && priority(c) <= priority(ops.top())) {
nums.push(processExpression(nums, ops));
}
ops.push(c);
} else if (c == '(') {
ops.push(c);
} else if (c == ')') {
while (ops.top() != '(') {
nums.push(processExpression(nums, ops));
}
ops.pop();
}
}
while (!ops.empty()) {
nums.push(processExpression(nums, ops));
}
return nums.top();
}
int main() {
string expr = "2*(3+4)-5/(6-2)";
int result = calculateExpression(expr);
cout << result << endl;
return 0;
}
```
在这个代码中,我们使用两个栈来处理表达式:一个存储数字,一个存储运算符。我们遍历表达式的每个字符,如果是数字,则继续读取下一个字符,直到读到一个非数字字符为止,并将整个数字压入数字栈中。如果是运算符,则将其与运算符栈中的运算符进行比较,如果当前运算符的优先级较低,则将运算符栈中的运算符弹出,并从数字栈中弹出两个数字进行计算,并将计算结果压入数字栈中,直到当前运算符的优先级高于栈顶运算符或者运算符栈为空为止。如果是左括号,则将其压入运算符栈中。如果是右括号,则将运算符栈中的运算符弹出,并从数字栈中弹出两个数字进行计算,并将计算结果压入数字栈中,直到找到左括号为止。最后,如果运算符栈中还有运算符,则将其弹出,并从数字栈中弹出两个数字进行计算,并将计算结果压入数字栈中,直到运算符栈为空为止。最终,数字栈中的唯一元素就是表达式的计算结果。