带括号的多位数带小数运算计算器c++代码
时间: 2023-09-02 12:06:11 浏览: 75
c++ 计算器 能实现带括号的小数计算
5星 · 资源好评率100%
以下是一个简单的带括号的多位数带小数运算计算器的C++代码:
```c++
#include <iostream>
#include <stack>
#include <string>
#include <vector>
using namespace std;
int priority(char op) {
if (op == '+' || op == '-') {
return 1;
} else if (op == '*' || op == '/') {
return 2;
} else {
return 0;
}
}
double calculate(double a, double b, char op) {
if (op == '+') {
return a + b;
} else if (op == '-') {
return a - b;
} else if (op == '*') {
return a * b;
} else if (op == '/') {
return a / b;
} else {
return 0;
}
}
double calculateExpression(const string& expr) {
stack<double> numStack;
stack<char> opStack;
vector<double> nums;
vector<char> ops;
int len = expr.length();
for (int i = 0; i < len; i++) {
char c = expr[i];
if (c == '(') {
opStack.push(c);
} else if (c == ')') {
while (opStack.top() != '(') {
char op = opStack.top();
opStack.pop();
double b = numStack.top();
numStack.pop();
double a = numStack.top();
numStack.pop();
double res = calculate(a, b, op);
numStack.push(res);
}
opStack.pop();
} else if (c >= '0' && c <= '9') {
double num = 0;
int j = i;
while (j < len && expr[j] >= '0' && expr[j] <= '9') {
num = num * 10 + (expr[j] - '0');
j++;
}
if (j < len && expr[j] == '.') {
double k = 1;
j++;
while (j < len && expr[j] >= '0' && expr[j] <= '9') {
k = k / 10;
num += k * (expr[j] - '0');
j++;
}
}
numStack.push(num);
i = j - 1;
} else {
while (!opStack.empty() && opStack.top() != '(' && priority(opStack.top()) >= priority(c)) {
char op = opStack.top();
opStack.pop();
double b = numStack.top();
numStack.pop();
double a = numStack.top();
numStack.pop();
double res = calculate(a, b, op);
numStack.push(res);
}
opStack.push(c);
}
}
while (!opStack.empty()) {
char op = opStack.top();
opStack.pop();
double b = numStack.top();
numStack.pop();
double a = numStack.top();
numStack.pop();
double res = calculate(a, b, op);
numStack.push(res);
}
return numStack.top();
}
int main() {
string expr;
cout << "请输入带括号的多位数带小数运算表达式:";
cin >> expr;
double res = calculateExpression(expr);
cout << "结果为:" << res << endl;
return 0;
}
```
该计算器支持加、减、乘、除四种基本运算,以及带括号的多位数带小数运算。例如,输入表达式 "2*(3+4.5)-5/2",输出结果为 "12.5"。
阅读全文