#include<iostream>
#include<stack>
using namespace std;
int f(const char* str, stack<char>& s)
{
int i = 0;
while(str[i] != '\0')
{
if(str[i] == '*')
{
char t = s.top();
s.pop();
t = (t-'0') * (str[i+1] - '0');
s.push(t + '0');
i += 2;
}
else if(str[i] == '/')
{
char t = s.top();
s.pop();
t = (t-'0') / (str[i+1] - '0');
s.push(t + '0');
i += 2;
}
else
{
s.push(str[i]);
i++;
}
}
while(!s.empty())
{
if(s.size() < 3)
{
break;
}
char t1 = s.top();
s.pop();
char t2 = s.top();
s.pop();
char t3 = s.top();
s.pop();
if(t2 == '+')
{
char t = (t3 - '0') + (t1 - '0');
s.push(t+'0');
}
else if(t2 == '-')
{
char t = (t3 - '0') - (t1 - '0');
s.push(t+'0');
}
}
int res = s.top() - '0';
return res;
}
int main()
{
stack<char> s;
char str[100] = {0};
cin>>str;
cout<<f(str,s)<<endl;
return 0;
}
栈的应用,实现简单的不带括号的四则运算
最新推荐文章于 2021-10-12 17:56:38 发布