栈——算术表达式
来源:互联网 发布:python界面编程 编辑:程序博客网 时间:2024/05/16 06:14
将一个算术表达式(即中缀形式)转化成其后缀形式,并算出答案。
#include <stdio.h>#include <string.h>#include <iostream>#include <stack>#include <algorithm>#include <stdlib.h>using namespace std;using namespace std;bool IsOperator(char ch){ char ops[] = "+-*/"; for (int i = 0; i < sizeof(ops) / sizeof(char); i++) { if (ch == ops[i]) return true; } return false;}// 比较两个操作符的优先级int Precedence(char op1, char op2){ if (op1 == '(') { return -1; } if (op1 == '+' || op1 == '-') { if (op2 == '*' || op2 == '/') { return -1; } else { return 0; } } if (op1 == '*' || op1 == '/') { if (op2 == '+' || op2 == '-') { return 1; } else { return 0; } }}// 中缀表达式转换成后缀表达式void inFix2PostFix(char* inFix, char* postFix){ int j = 0, len; char c; stack<char> st; len = strlen(inFix); for (int i = 0; i < len; i++) { c = inFix[i]; if (c == '(') st.push(c);//左括号 入栈 else if (c == ')')//右括号 寻找栈内的左括号 弹出左右括号 { while (st.top() != '(') { postFix[j++] = st.top(); st.pop(); } st.pop(); } else { if (!IsOperator(c)) st.push(c); else { while (!st.empty() && Precedence(st.top(), c) >= 0)//入栈元素优先级不高于栈顶元素 { postFix[j++] = st.top();//记下栈顶元素 st.pop();//栈顶元素出栈 } st.push(c);//入栈元素入栈 } } } while (!st.empty())//依次标记 出栈 { postFix[j++] = st.top(); st.pop(); } postFix[j] = 0;}// 后缀表达式求值程序double postFixEval(char* postFix){ stack<int> st; int len = strlen(postFix); char c; for (int i = 0; i < len; i++) { c = postFix[i]; if (IsOperator(c) == false) { int tmp=c-'0'; st.push(tmp);//字符变数字 } else { int op1, op2; int val; op1 = st.top(); st.pop(); op2 = st.top();//取栈顶两数 st.pop(); switch (c)//运算 { case '+': val = op1 + op2; break; case '-': val = op2 - op1; break; case '*': val = op1 * op2; break; case '/': val = op2 / op1; break; } st.push(val); } } return st.top();}int main(){ char inFix[100]; char postFix[100]; double val; while (1) { printf("enter an expression: "); gets(inFix); if (strlen(inFix) == 0) continue; printf("\n%s = ", inFix); inFix2PostFix(inFix, postFix); printf("%s = ", postFix); val = postFixEval(postFix); printf("%.3f\n", val); } return 0;}
0 1
- 栈——算术表达式
- 算术表达式的转换——算术表达树
- 数据结构 栈的应用——算术表达式求值
- 栈的应用——求解简单算术表达式值
- C语言程序设计实战——算术表达式
- 算法学习——算术表达式
- 双栈算术表达式
- 算术表达式(栈)
- 栈的算术表达式求值
- 双栈算术表达式求值
- 算术表达式的转换 栈
- 利用栈解析算术表达式
- 利用栈解析算术表达式
- 数据结构---栈:一般算术表达式
- 《C语言及程序设计》实践项目——算术运算符与算术表达式
- 算术运算符与算术表达式——分离各位数
- 算术符号和算术表达式——分离整数和小数部分
- 算术运算符与算术表达式——如何买玫瑰?
- 次方求模
- Base64 加密解密字符串的简单使用
- icinga 服务端-客户端安装配置
- 关于安卓跑马灯效果实现的课题研究
- HTML5开发中ping标签的用法及隐私追踪
- 栈——算术表达式
- Ubuntu Intellij IDEA 配置
- Problem N
- WebService
- 数据结构之排序算法实现(选自大话数据结构)
- solr入门之solr安全控制的研究和实践(二)
- c++作业4
- Problem-M
- 关于色温调节的一个 shader