HDU 1237 简单计算器(中缀表达式求值)
来源:互联网 发布:126邮箱ssl协议端口号 编辑:程序博客网 时间:2024/05/21 22:32
http://acm.hdu.edu.cn/showproblem.php?pid=1237
分析:
中缀表达式求值 题目中没有括号 代码里加了括号
首先知道运算符的优先关系
计算方法
设置两个栈 一个符号栈 一个数字栈
初始化符号栈 将一个 "#" 压入占中
将得到的字符串处理为只含有数字和运算符 末尾加入 "#"
扫描处理后的字符串
如果扫描为运算符 将该运算符与符号栈栈顶运算符比较
如果栈顶运算符优先级低于该运算符 该运算符入栈
如果栈顶运算符优先级等于该运算符 托括号操作 弹出栈顶运算符
如果栈顶运算符优先级高于该运算符 从数字栈中弹出两个数字与栈顶运算符运算 将计算结果重新压入数字栈 并将栈顶运算符弹出 该运算符入栈
如果扫描为数字 将数字压入数字栈
最后 数字栈栈顶元素即为结果
代码写的相当丑 还望指正
AC代码:
#include <stdio.h>#include <stdlib.h>#include <string.h>#include <ctype.h>#include <stack>using namespace std;char str[1005];char ans[1005][1005];char *Sep=" "; char *p; double calculate(double a,double b,char c){ if(c=='+') return a+b; if(c=='-') return a-b; if(c=='*') return a*b; if(c=='/') return a/b;}int judge(char p1,char p2){ if (p1=='+'||p1=='-'){ if (p2=='+'||p2=='-'||p2==')'||p2=='#') return 1; else return -1;} else if (p1=='*'||p1=='/'){ if (p2=='(') return -1; else return 1;} else if (p1=='('){ if (p2==')') return 0; else return -1;} else if (p1==')') return 1; else if (p1=='#'){ if (p2=='#') return 0; else return -1;} }int main (){ while (gets(str)){ int len=strlen(str); str[len]=' '; str[len+1]='#'; stack<char> S1; // 符号栈 stack<double> S2; // 数字栈 S1.push('#'); p=strtok(str,Sep); int l=0; memset(ans,0,sizeof(ans)); do{strcpy(ans[l++],p);}while((p=strtok(NULL,Sep))); if (!strcmp(ans[0],"0")&&l==2) break; int index=0; while (ans[index][0]!='#'||S1.top()!='#'){ if (!isdigit(ans[index][0])){// 为运算符 char temp=S1.top(); int tt=judge(temp,ans[index][0]); if (tt==-1){ S1.push(ans[index][0]);index++; } else if (tt==0){ S1.pop();index++; } else if (tt==1){ double a=S2.top(); S2.pop(); double b=S2.top(); S2.pop(); S2.push(calculate(b,a,S1.top())); S1.pop(); } } else {// 为数字 S2.push(atof(ans[index]));index++; }} printf ("%.2lf\n",S2.top()); } return 0;}
这里是前缀表达式和后缀表达式的求值 http://blog.csdn.net/mm__1997/article/details/72964903
阅读全文
0 0
- HDU 1237 简单计算器(中缀表达式求值)
- hdu 1237 简单计算器(表达式求值)
- 简单计算器求值(中缀表达式转化成后缀表达式)
- HDU 1237 简单计算器 表达式求值
- hdu 1237 简单计算器【最简单的表达式求值】
- HDU 1237(简单计算器)栈的应用-表达式求值
- 用C++实现中缀表达式求值即简单科学计算器的功能
- 中缀表达式求值(C++)
- 中缀表达式求值(Java)
- 中缀转后缀并求值(简单计算器的核心)
- [计蒜客 15504 百度的科学计算器(简单)]表达式求值
- 表达式求值(中缀转后缀及后缀表达式求值)
- 表达式求值(前缀、中缀、后缀)
- codevs 2178(中缀表达式求值)
- 中缀表达式求值整数
- 中缀表达式求值
- 中缀表达式直接求值
- 表达式求值(中缀)
- 一个牛逼的 字符串拷贝函数
- dubbox编译安装本地maven仓库
- 1089: 最短路入门2(道路重建)
- Docker容器通过独立IP暴露给局域网的方法
- 递归查找
- HDU 1237 简单计算器(中缀表达式求值)
- 并查集
- 编写代码模拟三次密码输入的场景。
- TP5 like模糊查询
- HDU 3072 Intelligence System 强连通缩点
- 代码整理
- css背景样式 列表样式 盒子模型 浮动
- Maximum Subsequence Sum
- 51nod-1380