用OPTR栈和OPND栈分别来存储运算符和操作数,以‘#’作为结束符号
输入ch,
若是操作数,压入OPND栈。
若是运算符,比较OPTR栈顶元素和ch的比较级关系
OPTR栈顶元素大于ch,弹出OPTR的运算符,从OPND中弹出两 个数,作计算并压入OPND中。
OPTR栈顶元素小于ch,将ch压入OPTR。
若ch为’(‘或’)’,另作比较级处理,方法如下表:
OPTR.top\ch | +- | */ | ( | ) |
---|---|---|---|---|
+- | 1 | 0 | 0 | 0 |
*/ | 1 | 1 | 0 | 1 |
( | 0 | 0 | 0 | 2 |
) | 2 | 2 | 2 | 2 |
0表示OPTR栈顶元素比较级小于ch
1表示OPTR栈顶元素比较级大于ch
2表示在OPTR中’)‘作为栈顶元素,上一个元素是’(’
比较级计算
int percede(char top,char ch){
if (top=='+'||top=='-'){
if(ch=='+'||ch=='-'||ch==')'){
return 1;
}
if (ch=='*'||ch=='/'||ch=='('){
return 0;
}
}
if (top=='*'||top=='/'){
if (ch=='+'||ch=='-'||ch=='*'||ch=='/'||ch==')'){
return 1;
}
if (ch=='('){
return 0;
}
}
if (top=='('){
if (ch==')'){
return 2;
}
else return 0;
}
if (top==')'){
return 2;
}
}
从键盘输入ch,如果是操作数,需要先转换成int类型,再存入OPND
int chartoint(char ch){
return int( ch )-48;
}
计算器函数
int cal(char ch,int a,int b){
if (ch=='+'){
return a+b;
}
if (ch=='-'){
return a-b;
}
if (ch=='*'){
return a*b;
}
if (ch=='/'){
return a/b;
}
}
源代码
#include <iostream>
#include <stack>
using namespace std;
int chartoint(char ch){//字符型向整型转换
return int( ch )-48;
}
int percede(char top,char ch){//优先级关系,1表示top高于ch,0表示top低于ch,2表示top和ch相等
if (top=='+'||top=='-'){
if(ch=='+'||ch=='-'||ch==')'){
return 1;
}
if (ch=='*'||ch=='/'||ch=='('){
return 0;
}
}
if (top=='*'||top=='/'){
if (ch=='+'||ch=='-'||ch=='*'||ch=='/'||ch==')'){
return 1;
}
if (ch=='('){
return 0;
}
}
if (top=='('){
if (ch==')'){
return 2;
}
else return 0;
}
if (top==')'){
return 2;
}
}
int cal(char ch,int a,int b){
if (ch=='+'){
return a+b;
}
if (ch=='-'){
return a-b;
}
if (ch=='*'){
return a*b;
}
if (ch=='/'){
return a/b;
}
}
void main()
{
char ch;
int a,b;
stack < char > OPTR;//运算符栈
stack < int > OPND;//操作数栈
cin>>ch;
while(ch!='#'){//表达式以#截止
if (ch=='+'||ch=='-'||ch=='*'||ch=='/'||ch=='('||ch==')'){//ch是运算符
if (OPTR.empty()||percede(OPTR.top(),ch)==0){//空栈或top优先级低于ch
OPTR.push(ch);
}
else if (percede(OPTR.top(),ch)==1){//top优先级高于ch
b=OPND.top();
OPND.pop();
a=OPND.top();
OPND.top()=cal(OPTR.top(),a,b);
OPTR.top()=ch;
}
else if (percede(OPTR.top(),ch)==2){//'('匹配到')'
OPTR.pop();
OPTR.top()=ch;
}
}
else {//ch是操作数
OPND.push(chartoint(ch));//入栈
}
cin>>ch;
}
while (!OPTR.empty()){//运算栈中仍有运算符
if (OPTR.top()==')'){
OPTR.pop();
OPTR.pop();
}
else {
b=OPND.top();
OPND.pop();
a=OPND.top();
OPND.top()=cal(OPTR.top(),a,b);
OPTR.pop();
}
}
cout<<OPND.top();
system("pause");
}
计算 (3*4+2)+(6/2-1)#