#include <bits/stdc++.h>
using namespace std;
stack<char>st;
stack<double>cal;
char s[1200],post[1200];
double res;
//中缀转后缀
void trans()
{
while(!st.empty())
st.pop();
int i=0,j=0;
char ch;
while(s[i]){
ch=s[i];
if(s[i]=='(')
st.push(s[i]);
else if(ch==')')
{
while(!st.empty()&&st.top()!='(')
{
post[j++]=st.top();
post[j++]=' ';
st.pop();
}
st.pop();
}
else if(ch=='+'||ch=='-')
{
while(!st.empty()&&st.top()!='(')
{
post[j++]=st.top();
post[j++]=' ';
st.pop();
}
st.push(ch);
}
else if(ch=='*'||ch=='/')
{
while(!st.empty()&&st.top()!='('&&(st.top()!='+')&&(st.top()!='-'))
{
post[j++]=st.top();
post[j++]=' ';
st.pop();
}
st.push(ch);
}
else
{
while(ch>='0'&&ch<='9')
{
post[j++]=ch;
i++;
if(s[i]) ch=s[i];
else break;
}
post[j++]=' ';
i--;
}
i++;
}
while(!st.empty())
{
post[j++]=st.top();
post[j++]=' ';
st.pop();
}
j--;
post[j]='\0';
}
//输出后缀表达式的值
void work(char *s)
{
double n1,n2;
double d=0;
int i=0;
while(!cal.empty())
{
cal.pop();
}
int len=strlen(post);
while(i<len)
{
if(s[i]>='0'&&s[i]<='9')
{
d=0;
while(s[i]>='0'&&s[i]<='9')
{
d=d*10+(s[i]-48);
i++;
}
cal.push(d);
}
else if(s[i]=='+')
{
n2=cal.top();
cal.pop();
n1=cal.top();
cal.pop();
cal.push(n1+n2);
}
else if(s[i]=='-')
{
n2=cal.top();
cal.pop();
n1=cal.top();
cal.pop();
cal.push(n1-n2);
}
else if(s[i]=='*')
{
n2=cal.top();
cal.pop();
n1=cal.top();
cal.pop();
cal.push(n1*n2);
}
else if(s[i]=='/')
{
n2=cal.top();
cal.pop();
n1=cal.top();
cal.pop();
cal.push(n1/n2);
}
i++;
}
cout<<cal.top()<<endl;
}
int main()
{
while(gets(s)!=NULL)
{
trans();
//输出后缀表达式
puts(post);
//输出结果
work(post);
}
return 0;
}
栈实现简单计算器的四则运算(STL)
最新推荐文章于 2021-08-06 21:51:58 发布