对于普通的四则混合运算,可以将表达式通过转换成逆波兰式来进行计算。具体是通过栈来进行实现的,代码如下:
代码:
#include<iostream>
#include<cstdio>
#include<stack>
#include<sstream>
#include<string>
using namespace std;
string in, post;
stack<char>st;
stack<int>p;
void i2s(string str, int& num)
{
stringstream ss;
ss << str;
ss >> num;
}
void turn() //中缀表达式转换成后缀表达式
{
int i;
char ch;
for (i = 0; i < (int)in.size(); ++i) {
switch (in[i])
{
case '+':
case '-':
if (!st.empty() && st.top() != '(') {
post.push_back(st.top());
st.pop();
}
st.push(in[i]);
break;
case '*':
case '/':
if (!st.empty() && (st.top() == '*' || st.top() == '/')) {
post.push_back(st.top());
st.pop();
}
st.push(in[i]);
break;
case '(':
st.push(in[i]);
break;
case ')':
ch = st.top(); st.pop();
post.push_back(ch);
st.pop();
break;
default:
while ('0' <= in[i] && in[i] <= '9') {
post.push_back(in[i]);
++i;
}
post.push_back('#'); i--;
break;
}
}
while (!st.empty()) {
post.push_back(st.top());
st.pop();
}
}
int cal() //通过后缀表达式计算,获得结果
{
int i, x, a, b;
string num;
for (i = 0; i < (int)post.size(); ++i) {
if ('0' <= post[i] && post[i] <= '9') {
while ('0' <= post[i] && post[i] <= '9')
num.push_back(post[i++]);
i2s(num, x); p.push(x); num.clear();
}
else {
b = p.top(); p.pop();
a = p.top(); p.pop();
switch (post[i])
{
case '+':
x = a + b;
break;
case '-':
x = a - b;
break;
case '*':
x = a * b;
break;
case '/':
x = a / b;
break;
default:
break;
}
p.push(x);
}
}
return p.top();
}
int main()
{
int i, j;
cin >> in;
turn();
cout << cal() << endl;
return 0;
}
/*
1+2*3
((1+2)*3+5)*6
*/