计算表达式
来源:互联网 发布:淘宝店铺设置满包邮 编辑:程序博客网 时间:2024/04/29 19:47
看了紫书上的表达式树,上面讲用递归来建树,并给出了代码,稍加改造就可以用来求表达式的值。
这让我想起了以前看的一篇博客 http://blog.csdn.net/yzl_rex/article/details/7745341
讲的是如何利用栈来求四则运算表达式的值。但计算前需要将中缀表达式转为后缀表达式。
上面有基本的理论+详细的步骤,写的很不错。
以下是自己写的代码
#include<stdio.h>#include<iostream>#include<string>#include<queue>#include<stack>#include<vector>#include<string.h>#define maxn 10010using namespace std;char str[maxn];int cal(int a,int b,char ch){ switch(ch) { case '+':return a+b; case '-':return a-b; case '*':return a*b; case '/':return a/b; } return 0;}struct Element{ bool isnum; int num; char ch; Element(bool a,int b,char c):isnum(a),num(b),ch(c){}};int main(){ vector<Element>vec; gets(str); int l=strlen(str); for(int i=0;i<l;i++) { if(str[i]==' ') continue; if(str[i]>='0'&&str[i]<='9') { int num=str[i]-'0'; int r=i+1; while(str[r]==' '||(str[r]>='0'&&str[r]<='9')) { if(str[r]==' ') { r++; continue; } num*=10; num+=str[r]-'0'; r++; } vec.push_back(Element(true,num,0)); i=r-1; } else vec.push_back(Element(false,0,str[i])); } queue<Element>q; stack<Element>s; /* for(unsigned int i=0;i<vec.size();i++) if(vec[i].isnum) printf("%d ",vec[i].num); else printf("%c ",vec[i].ch); puts(""); */ for(unsigned int i=0;i<vec.size();i++) if(vec[i].isnum) q.push(vec[i]); else { if(vec[i].ch==')') { while(s.top().ch!='(') { q.push(s.top()); s.pop(); } s.pop(); } else if(vec[i].ch=='('||vec[i].ch=='*'||vec[i].ch=='/') s.push(vec[i]); else { if(!s.empty()&&(s.top().ch=='*'||s.top().ch=='/')) { while(!s.empty()&&s.top().ch!='('&&s.top().ch!=')') { q.push(s.top()); s.pop(); } } s.push(vec[i]); } } while(!s.empty()) { q.push(s.top()); s.pop(); } /* while(!q.empty()) { if(q.front().isnum) printf("%d ",q.front().num); else printf("%c ",q.front().ch); q.pop(); } puts(""); */ while(!q.empty()) { if(q.front().isnum) {s.push(q.front());q.pop();} else { Element e=q.front(); q.pop(); Element e1=s.top(); s.pop(); Element e2=s.top(); s.pop(); s.push(Element(true,cal(e2.num,e1.num,e.ch),0)); } } printf("%d\n",s.top().num); return 0;}/*9+(3-1)*3+10/2 ( 9 + ( 3 - 1 ) * 3 + 1 0 / 2 )((1 8 /(( 1+ 2)* 3)) +3) * 5*/
0 0
- 表达式计算
- 表达式计算
- 表达式计算
- 表达式计算
- 表达式计算
- 表达式计算
- 表达式计算
- 计算表达式
- 表达式计算
- 表达式计算
- 表达式计算
- 表达式计算
- 表达式计算 .
- 计算表达式
- 计算表达式
- 表达式计算
- 表达式计算
- 表达式计算
- android检查网络连接
- Android实现数据存储技术
- Web.py - streaming_large_files
- Search in Rotated Sorted Array
- request对象
- 计算表达式
- 【千里码】Task6-IP
- bzoj 1592 [Usaco2008 Feb]Making the Grade 路面修整
- 浅谈数位DP(以hihocoder #1033 交错和为例)
- 将图像扭正确。利用OpenCV检测图像中的长方形画布或纸张并提取图像内容
- hello world 是我们的第一个脚印!
- LWIP内存池memp.h头文件学习
- Linux mv 重命名文件问题
- 【bzoj1191】【HNOI2006】【超级英雄】【Hero】【二分图匹配】