带括号的多位数运算计算器c++代码
时间: 2023-09-01 16:10:28 浏览: 61
以下是一个简单的带括号的多位数运算计算器的C++代码:
```c++
#include <iostream>
#include <stack>
#include <string>
#include <sstream>
using namespace std;
int calculate(string s) {
stack<int> nums;
stack<char> ops;
int num = 0;
char op = '+';
for (int i = 0; i < s.length(); i++) {
char c = s[i];
if (isdigit(c)) {
num = num * 10 + (c - '0');
}
if ((!isdigit(c) && c != ' ') || i == s.length() - 1) {
if (op == '+') {
nums.push(num);
}
else if (op == '-') {
nums.push(-num);
}
else if (op == '*') {
int n = nums.top();
nums.pop();
nums.push(n * num);
}
else if (op == '/') {
int n = nums.top();
nums.pop();
nums.push(n / num);
}
num = 0;
op = c;
}
if (c == '(') {
ops.push(op);
op = '+';
}
if (c == ')') {
while (ops.top() != '(') {
char o = ops.top();
ops.pop();
int n2 = nums.top();
nums.pop();
int n1 = nums.top();
nums.pop();
if (o == '+') {
nums.push(n1 + n2);
}
else if (o == '-') {
nums.push(n1 - n2);
}
else if (o == '*') {
nums.push(n1 * n2);
}
else if (o == '/') {
nums.push(n1 / n2);
}
}
ops.pop();
}
}
while (!ops.empty()) {
char o = ops.top();
ops.pop();
int n2 = nums.top();
nums.pop();
int n1 = nums.top();
nums.pop();
if (o == '+') {
nums.push(n1 + n2);
}
else if (o == '-') {
nums.push(n1 - n2);
}
else if (o == '*') {
nums.push(n1 * n2);
}
else if (o == '/') {
nums.push(n1 / n2);
}
}
return nums.top();
}
int main() {
string s;
getline(cin, s);
cout << calculate(s) << endl;
return 0;
}
```
该代码使用两个栈来处理运算符和操作数,并使用stringstream来将多位数字转换为整数。它还使用了逆波兰表达式的思想处理括号内的表达式。