#include <iostream>
#include <stack>
#include <math.h>
#define maxsize 20
using namespace std
;
class Calculator
{
public:
Calculator(){while(s
.empty()==false)s
.pop();}
void Run(char *ch
);
void Clear();
private:
stack
<int> s
;
void AddOperator(int value
);
bool Get2Operands(int& left
,int& right
);
void DoOperator(char op
);
};
void Calculator
::DoOperator(char op
)
{
int left
,right
,value
;
bool result
;
result
=Get2Operands(left
,right
);
if(result
==true)
switch(op
){
case'+':value
=left
+right
;s
.push(value
);break;
case'-':value
=left
-right
;s
.push(value
);break;
case'*':value
=left
*right
;s
.push(value
);break;
case'/':if(right
==0.0){
cerr
<<"Divide by 0!"<<endl
;
Clear();
}
else{
value
=left
/right
;s
.push(value
);
}
break;
}
else Clear();
}
bool Calculator
::Get2Operands(int &left
,int& right
)
{
if(s
.empty()==true){
cerr
<<"缺少右操作数!"<<endl
;
return false;
}
right
=s
.top();
s
.pop();
if(s
.empty()==true){
cerr
<<"缺少左操作数!"<<endl
;
return false;
}
left
=s
.top();
s
.pop();
return true;
}
void Calculator
::AddOperator(int value
)
{
s
.push(value
);
}
void Calculator
::Run(char *ch
)
{
int newOperand
;
char *p
=ch
;
while(*p
!='#'){
switch(*p
){
case'+':
case'-':
case'*':
case'/':DoOperator(*p
);break;
default://cin
.putback(*p
);
newOperand
=*p
-48;
AddOperator(newOperand
);
}
p
++;
}
cout
<<"="<<s
.top()<<endl
;
}
void Calculator
::Clear()
{
while(s
.size()>0)
s
.pop();
}
int isp(char ch
)
{
int num
=-1;
switch(ch
){
case'#':num
=0;break;
case'(':num
=1;break;
case'*':
case'/':
case'%':num
=5;break;
case'+':
case'-':num
=3;break;
case')':num
=6;break;
}
return num
;
}
int icp(char ch
)
{
int num
=-1;
switch(ch
){
case'#':num
=0;break;
case'(':num
=6;break;
case'*':
case'/':
case'%':num
=4;break;
case'+':
case'-':num
=2;break;
case')':num
=1;break;
}
return num
;
}
void postfix()
{
stack
<char> s
;
char ch
='#',ch1
,op
,p
[maxsize
];
int i
=0;
s
.push(ch
);
cin
.get(ch
);
while(s
.empty()==false && ch
!='#')
if(isdigit(ch
)){
cout
<<ch
;
p
[i
]=ch
;i
++;
cin
.get(ch
);
}
else{
ch1
=s
.top();
if(isp(ch1
)<icp(ch
)){
加粗样式 s
.push(ch
);
cin
.get(ch
);
}
else if(isp(ch1
)>icp(ch
)){
op
=s
.top();
s
.pop();
cout
<<op
;
p
[i
]=op
;i
++;
}
else{
op
=s
.top();
s
.pop();
if(op
=='(')
cin
.get(ch
);
}
}
Calculator CAL
;
CAL
.Run(p
);
}
int main()
{
postfix();
system("pause");
return 0;
}
转载请注明原文地址: https://lol.8miu.com/read-10792.html