问题描述:
输入一个只包含个位数字的简单四则运算表达式字符串,计算该表达式的值
注:1、表达式只含+, -, *, / 四则运算符,不含括号
2、表达式数值只包含个位整数(0-9),且不会出现0作为除数的情况
3、要考虑加减乘除按通常四则运算规定的计算优先级
4、除法用整数除法,即仅保留除法运算结果的整数部分。比如8/3=2。输入表达式保证无
0作为除数情况发生
5、输入字符串一定是符合题意合法的表达式,其中只包括数字字符和四则运算符字符和(),除
此之外不含其它任何字符,不会出现计算溢出情况
利用后缀式计算,若是数字则直接入栈,若是运算符则出栈两次,进行计算,并把结果再入栈。
#include <iostream>
#include <stack>
using namespace std;
//中缀转后缀
int cmp(char c1,char c2)//相同为0,
{
int v1=0,v2=0;
if(c2=='#')
return -1;
if(c1=='+' || c1=='-')
v1=1;
if(c1=='*' || c1=='/')
v1=2;
if(c2=='+' || c2=='-')
v2=1;
if(c2=='*' || c2=='/')
v2=2;
return v2-v1;
}
void change(char *p1,char *p2)
{
stack<char> st;
st.push('#');
int i=0,j=0;
int len=strlen(p1);
for(i=0;i<len;i++)
{
if(p1[i]>='0' && p1[i]<='9')
p2[j++]=p1[i];
if(p1[i]=='+'||p1[i]=='-'||p1[i]=='*'||p1[i]=='/')
{
if(cmp(st.top(),p1[i])>0)
{
st.push(p1[i]);
}
else
{
while(st.top()!='#' && cmp(st.top(),p1[i])<=0)
{
p2[j++]=st.top();
st.pop();
}
st.push(p1[i]);
}
}
}
while(st.top()!='#')
{
p2[j++]=st.top();
st.pop();
}
p2[j]='\0';
}
void compute(char *p)
{
stack<int> st;
for(int i=0;i<strlen(p);i++)
{
if(p[i]>='0' && p[i]<='9')
{
st.push(p[i]-'0');
}
else
{
int n=0;
int n1=st.top();
st.pop();
int n2=st.top();
st.pop();
if(p[i]=='+')
n=n1+n2;
else if(p[i]=='-')
n=n2-n1;
else if(p[i]=='*')
n=n1*n2;
else if(p[i]=='/')
n=n2/n1;
st.push(n);
}
}
cout<<st.top()<<endl;
}
int main()
{
char p1[100];
char p2[100];
cin>>p1;
change(p1,p2);
cout<<p2<<endl;
compute(p2);
system("pause");
}