利用2个栈的思路,一个栈存储数,一个栈存储操作符。
计算表达式最后需要有’='号,例如
(37-5)/4*3=
此外,这个代码无法计算带小数点的算式,有待改进。
代码如下:
#include <iostream>
#include <string>
#include <stack>
#include <map>
using namespace std;
bool isDigital(char A) {
if (A >= '0'&&A <= '9') {
return true;
}
else
return false;
}
double exec(double a, double b, char op) {
switch (op)
{
case'+':
return a + b;
case'-':
return a - b;
case'*':
return a * b;
case'/':
return a / b;
}
}
double calcStr(string rstr)
{
double result;
map<char, int> isp;
map<char, int> icp;
isp['='] = icp['='] = 0;
isp['('] = icp[')'] = 1;
isp[')'] = icp['('] = 6;
isp['+'] = isp['-'] = 3;
isp['*'] = isp['/'] = 5;
icp['+'] = icp['-'] = 2;
icp['*'] = icp['/'] = 4;
stack<char> op;
stack<double> nums;
op.push('=');
int index = 0;
while (rstr[index] !='=') {
double tmp = 0;
if (isDigital(rstr[index])) { //多位数字处理
while (isDigital(rstr[index])) {
tmp = (tmp * 10) + (rstr[index] - '0');
index++;
}
nums.push(tmp);
}
else if (icp[rstr[index]] > isp[op.top()]) {
op.push(rstr[index]);
index++;
}
else if (icp[rstr[index]] < isp[op.top()]) {
double rnum = nums.top();
nums.pop();
double lnum = nums.top();
nums.pop();
double tmpRes = exec(lnum, rnum, op.top());//算出结果
op.pop();
nums.push(tmpRes);
}
else {
if (op.top() == '(') {
op.pop();
index++;
}
}
}
while (op.top() != '=') {
double rnum = nums.top();
nums.pop();
double lnum = nums.top();
nums.pop();
double tmpRes = exec(lnum, rnum, op.top());//算出结果
op.pop();
nums.push(tmpRes);
}
result = nums.top();
return result;
}
int main()
{
string inputString;
cin >> inputString;
cout << inputString << calcStr(inputString) << endl;
}