简单的表达式求值
2015-08-31 10:55
225 查看
#include <bits/stdc++.h> using namespace std; #define M 100 char ops[7] = {'+', '-', '*', '/', '(', ')', '='}; char cmp[7][7]= {{'>', '>', '<', '<', '<', '>', '>'}, {'>', '>', '<', '<', '<', '>', '>'}, {'>', '>', '>', '>', '<', '>', '>'}, {'>', '>', '>', '>', '<', '>', '>'}, {'<', '<', '<', '<', '<', '=', ' '}, {'>', '>', '>', '>', ' ', '>', '>'}, {'<', '<', '<', '<', '<', ' ', '='} }; bool check(char ch) { for (int i = 0; i < 7; i++) if (ch == ops[i]) return true; return false; } char C(char ch1, char ch2) { int i, m, n; for (i = 0; i < 7; i++) { if (ch1 == ops[i]) m = i; if (ch2 == ops[i]) n = i; } return cmp[m] ; } void cal(int x, char op, int y, int &z) { switch (op) { case '+': z = x + y; break ; case '-': z = x - y; break ; case '*': z = x * y; break ; case '/': z = x / y; break ; } } void work(char *str, int &result) { int a, b, v; char ch, op; int temp, i = 0; stack <char> oper; stack <int> num; oper.push('='); ch = str[i++]; while (ch != '=' || oper.top() != '=') { if (check(ch)) { switch (C(oper.top(), ch)) { case '<': oper.push(ch); ch = str[i++]; break; case '=': oper.pop(); ch = str[i++]; break; case '>': op = oper.top(); oper.pop(); b = num.top(); num.pop(); a = num.top(); num.pop(); cal(a, op, b, v); num.push(v); break; } } else { temp = ch - '0'; num.push(temp); ch=str[i++]; } } result = num.top(); printf("%d\n",result); } int main() { int i = 0; int result; char *str; str = new char[M]; cin >> str[i]; while (str[i] != '=') { cin >> str[++i]; } work(str, result); return 0; }
相关文章推荐
- 数据结构学习之路-第二章:双向链表
- 网站优化:引用CDN公共库
- JavaScript 键盘event.keyCode值列表大全
- C++——设计模式说明
- [C#技术] .NET平台开源JSON库LitJSON的使用方法(转载)
- C# 压缩文件夹及文件
- android:windowSoftInputMode属性详解
- Eclipse Tomcat 404
- gulp顺序执行任务
- bootloader与app区域代码重叠导致进入HardFault_Handler!
- 【C#】关于HttpContext.Current.Request.QueryString 你要知道点
- C++——派生类中的访问——可见性问题
- C++——内存使用
- 搜索框(附带事件函数)
- 处理HP-UNIX面板灯报警及配置MP
- Java数组练习冒泡排序
- terminate_handler unexpectedly threw an exception
- 迷宫问题——回溯法解
- struct字节对齐
- Ubuntu下Thunderbird和exchange配置