中缀表达式求值
直接上代码!
在这里插入代码片
#include<iostream>
#include<stack>
#include<string>
using namespace std;
typedef struct opera
{
char ch;
int level;
}Oper;
Oper str[10] = {{'+',2}, {'-',2}, {'*',3}, {'/',3}, {'%',3},{'(',1}};
stack<int> S1;
stack<Oper> S2;
void func();
int main()
{
cout << "请输入表达式!!" << endl;
string s;
cin >> s;
for (int i = 0; i < s.size(); i++)
{
if (s[i] >= '0' && s[i] <= '9')
{
int j = i + 1;
int cnt = s[i] - '0';
while (s[j] >= '0' && s[j] <= '9')
{
cnt = cnt * 10 + (s[j] - '0');
j++;
}
S1.push(cnt);
i = j - 1;
}
else
{
if (s[i] == '(')
{
Oper t;
t.ch = '(';
t.level = 1;
S2.push(t);
}
else if (s[i] == ')')
{
while (S2.top().ch != '(')
{
func();
}
S2.pop();
}
else
{
if (S2.empty())
{
for (int k = 0; k < sizeof(str) / sizeof(str[0]); k++)
{
if (s[i] == str[k].ch) {
S2.push(str[k]);
break;
}
}
}
else
{
for (int k = 0; k < sizeof(str) / sizeof(str[0]); k++)
{
if (s[i] == str[k].ch)
{
if (str[k].level > S2.top().level) S2.push(str[k]);
else
{
func();
S2.push(str[k]);
}
}
}
}
}
}
}
while (!S2.empty())
{
func();
}
cout << "结果为:" << S1.top();
return 0;
}
void func()
{
int first = S1.top();
S1.pop();
int second = S1.top();
S1.pop();
int res = 0;
switch (S2.top().ch)
{
case '+': res = first + second;
break;
case '-': res = second - first;
break;
case '*': res = second * first;
break;
case '/': res = second / first;
break;
case '%': res = second % first;
break;
default:
break;
}
S1.push(res);
S2.pop();
}