表达式计算模板
2017-03-26 22:08
253 查看
#include<iostream> #include<cstring> #include<stack> #include<algorithm> #include<cmath> using namespace std; stack<char> s1,s2; stack<int> s3; char ch[150]={0};//用来存表达式 int num[11];//用来暂时存数字 int priority(char ch)//用于比较字符优先级 { if(ch==')') return 1; if(ch=='+'||ch=='-') return 2; if(ch=='*'||ch=='/') return 3; if(ch=='(') return 4; } int Scal(int x,int y,char ope)//两个数的运算 { if(ope=='+') return x+y; if(ope=='-') return x-y; if(ope=='*') return x*y; if(ope=='/'&&y!=0) return x/y; } void Transform(int n)//将中缀表达式转化为后缀表达式 { int k=0; for(int i=0;i<n;i++) { if(ch[i]>='0'&&ch[i]<='9')//当是数字的情况 { if(i+1<n&&(ch[i+1]<'0'||ch[i+1]>'9')||i==n-1)//当是最后一个数字,或下一个元素是运算符 { s2.push(ch[i]); s2.push('#'); } else s2.push(ch[i]); } else { if(s1.empty()||ch[i]=='('||priority(ch[i])>priority(s1.top()))//当是运算符,有3种情况直接入栈 s1.push(ch[i]); else if(ch[i]==')')//当是右括号的情况 { while(s1.top()!='(') { s2.push(s1.top()); s1.pop(); } s1.pop(); } else//当运算符优先级小于或等于S1栈顶运算符的优先级 { while(!s1.empty()&&priority(ch[i])<=priority(s1.top())&&s1.top()!='(')//这里还要注意两个界限 { s2.push(s1.top()); s1.pop(); } s1.push(ch[i]); } } } while(!s1.empty())//当表达式结束 { s2.push(s1.top()); s1.pop(); } while(!s2.empty()) //将栈内元素放回S2中 { ch[k++]=s2.top(); s2.pop(); } reverse(ch,ch+k);//将ch[]反向 ch[k]=0; } int Cal(int n)//后缀表达式计算 { int x,y,tmp=0,k=0; for(int i=0;i<n;i++) { if(ch[i]=='#')//是#直接跳过 continue; else if(ch[i]=='+'||ch[i]=='-'||ch[i]=='*'||ch[i]=='/')//是运算符弹出栈顶两元素计算后放回栈 { x=s3.top(); s3.pop(); y=s3.top(); s3.pop(); x=Scal(y,x,ch[i]); s3.push(x); } else//是数字字符 { if(ch[i+1]=='#')//下一个元素是# { num[k++]=ch[i]-'0'; for(int i=0;i<k;i++) tmp+=(num[i]*(int)pow(10,k-i-1)); s3.push(tmp); tmp=0; k=0; } else//下一个元素不是# { num[k++]=ch[i]-'0'; } } } return s3.top(); } int main() { gets(ch); Transform(strlen(ch)); cout<<Cal(strlen(ch))<<endl; return 0; }
相关文章推荐
- 表达式计算模板
- C++计算四则表达式的模板
- 表达式计算模板(+-*/^)
- 四则表达式计算模板第二版
- 堆栈应用:表达式计算
- [0613]Tyvj P1040-P1042 表达式的计算1-3
- 表达式计算算法总结
- 自己写的程序expr,以计算从命令行输入的逆波尔表达式的值,其中每个运算符或操作数用一个单独的参数表示
- 中缀表达式转后缀表达式并计算
- 计算一个序列的移动平均线序列的模板,可实现均线的均线
- 九度[1101]计算表达式
- 计算几何_模板
- 栈的应用——计算表达式
- 表达式计算
- delphi计算表达式的值
- <队内胡策> 2017.10.24 求逆序对+表达式计算+贪心+Bfs+最短路、exgcd
- 我就给一个PHP逆波兰表达式的算法吧---工资计算专用
- 表达式(四则运算)计算的算法
- setInterval() 方法可按照指定的周期(以毫秒计)来调用函数或计算表达式
- 实际工作中遇到的技术难题与大家交流(工作流条件表达式计算部分),希望技术高手能给于指点