表达式求值
2013-11-02 22:52
302 查看
#include "stdio.h" #include "string.h" #include "math.h" const int NO=105; struct OP{ char s[NO]; int top; }op; struct DA{ double s[NO]; int top; }da; char comp(char ch1,char ch2) { char s[]={'+','-','*','/','(',')','#','^'}; char ss[8][8]={ '>','>','<','<','<','>','>','<', '>','>','<','<','<','>','>','<', '>','>','>','>','<','>','>','<', '>','>','>','>','<','>','>','<', '<','<','<','<','<','=','E','<', '>','>','>','>','E','>','>','>', '<','<','<','<','<','E','=','<', '>','>','>','>','<','>','>','<', }; int aaa[256]; for(int i=0;i<8;i++) aaa[s[i]]=i; return ss[aaa[ch1]][aaa[ch2]]; } double cal(double a,char ch,double b) { switch(ch) { case '+':return a+b; break; case '-':return a-b; break; case '*':return a*b; break; case '/':return a/b; break; case '^':return pow(a,b);break; } } double expresion(char s[]) { char temp[105]; double result,n; op.top=0; da.top=0; op.s[++op.top]='#'; int i=0,j=0; while(s[i]!='#' || op.s[op.top]!='#') { if(i==0 && s[0]=='-' || (s[i]=='-' && s[i-1]=='(')) da.s[++da.top]=0; if(s[i]>='0' && s[i]<='9' ||s[i]=='.') { int k=0; while(s[i]>='0' && s[i]<='9' ||s[i]=='.') { temp[k++]=s[i++]; } temp[k]='\n'; sscanf(temp,"%lf",&da.s[++da.top]); } else switch(comp(op.s[op.top],s[i])) { case '>': n=cal(da.s[da.top-1],op.s[op.top--],da.s[da.top]); da.top-=2; da.s[++da.top]=n; break; case '<': op.s[++op.top]=s[i]; i++; break; case '=': op.top--; i++; break; } } return da.s[da.top]; } int main() { char s[NO]; gets(s); strcat(s,"#"); printf("%.3f\n",expresion(s)); return 0; }
相关文章推荐
- struts2的防止表单重复提交
- Github 使用
- Redis集群方案
- 简单工厂设计模式
- 范式
- 深入剖析MongoDB架构
- hdu-1575矩阵快速幂
- 基于antlr的表达式解析器——函数类型验证
- Hadoop处理大量小文件的问题和解决方法
- Binwalk:后门(固件)分析利器
- shell脚本攻略学习笔记(八)当个好管家
- 【C++学习笔记】在控制台绘Bitmap
- 2014年托福考试共计全国38场考试
- hud1211旋转百花
- 队列
- 判断IP地址的类型
- HDU-1044 Collect More Jewels BFS + DFS
- 九度OJ 1202:排序
- 阻止事件(取消其默认行为并阻止其传播)
- 话说Chrome进程体系与插件管理