#include <iostream>
#include <stack>
#include <string>
using namespace std;
bool isopretor(char ch)
{
switch(ch)
{
case '+' :
case '-':
case '*':
case '/':
case '%':
return 1;
default:
return -1;
}
}
int priority(char ch)
{
switch(ch)
{
case '*':
case '/':
case '%':
return 2;
case '(':
return 0;
case '+':
case '-':
return 1;
case '#':
return -1;
default:
return -1;
}
}
void postfix(string &pre,char post[],int &len)
{
int i=0,j=0;
stack<char>mystack;
mystack.push('#');
while (pre[i]!='#')
{
if (pre[i]=='(')
{
mystack.push(pre[i]);
}else if ( (pre[i]>='0' && pre[i]<='9')||pre[i]== '.')
{
post[j++]=pre[i];
}
else if (pre[i]==')')
{
while(mystack.top()!='(')
{
post[j++]=mystack.top();
mystack.pop();
}
mystack.pop();
}
else if (isopretor(pre[i]))
{
post[j++]=' ';
while(priority(pre[i])<=priority(mystack.top()))
{
post[j++]=mystack.top();
mystack.pop();
}
mystack.push(pre[i]);
}
i++;
}
while (mystack.top()!='#')//模板类stack top方法报错当没有元素时
{
post[j++]=mystack.top();
mystack.pop();
}
post[j]='#';
len=j;
}
//把字符串数据转为数字存下来
double read_num(char *post,int &i)
{
double sum=0;
while (post[i]>='0'&&post[i]<='9')
{
sum=sum*10+post[i]-'0';
i++;
}
int k=0;
if (post[i]=='.')
{
i++;
while (post[i]>='0'&&post[i]<='9')
{
sum=sum*10+post[i]-'0';
i++;k++;
}
}
if (k!=0)
{
sum/=pow(10.0,k);
}
return sum;
}
//计算逆波兰的值
double postValue(char *post)
{
stack<double>mystack;
double x1,x2;
int i=0;
while (post[i]!='#')
{
if (post[i]>='0'&&post[i]<='9')
{
mystack.push(read_num(post,i));
}
else if (post[i]==' ')
{
i++;
}
else if (post[i]=='+')
{
x2=mystack.top();
mystack.pop();
x1=mystack.top();
mystack.pop();
mystack.push(x1+x2);
i++;
}
else if (post[i]=='-')
{
x2=mystack.top();
mystack.pop();
x1=mystack.top();
mystack.pop();
mystack.push(x1-x2);
i++;
}
else if (post[i]=='*')
{
x2=mystack.top();
mystack.pop();
x1=mystack.top();
mystack.pop();
mystack.push(x1*x2);
i++;
}
else if (post[i]=='/')
{
x2=mystack.top();
mystack.pop();
x1=mystack.top();
mystack.pop();
mystack.push(x1/x2);
i++;
}
else if (post[i]=='%')
{
x2=mystack.top();
mystack.pop();
x1=mystack.top();
mystack.pop();
mystack.push((int)x1%(int)x2);
i++;
}
}
return mystack.top();
}
int main()
{
string pre="(2+4)*5+(5-2)/2#";
char post[100];
int len=0;
postfix(pre,post,len);//转成逆波兰
for (int i=0;i<len;i++)
{
cout<<post[i];
}
cout<<endl;
cout<<postValue(post)<<endl;
}
逆波兰实现计算器
最新推荐文章于 2021-11-02 01:06:14 发布