栈问题2(四则运算)
来源:互联网 发布:嘉合信网络信息技术 编辑:程序博客网 时间:2024/06/05 16:11
利用栈实现形如 a+b*c+(d*e+f)*g 的运算
先从中缀式转为后缀式 然后再计算 可输入空格
#include<iostream>#include<stack>#include<cstdio>using namespace std;//a+b*c+(d*e+f)*g //1+1*1+(2*1+1)*2 = 8//3 + 5 * 1 + ( 2 * 0 + 1 ) * 1 = 9//20+3*6+(1+1)*9 = 56int main(){ char Operator[10] = { '+','-','*','/','(',')' }; stack<char> st; stack<int> sum; char s[50],o[50]; //s存放输入 o存放操作符 int num[50]; //存储数字 int nc, oc; //nc数字数量 oc操作符数量 while(gets_s(s)) { while (!st.empty()) st.pop(); while (!sum.empty()) sum.pop(); nc = oc = 0; //中缀转后缀 for (int i = 0; i < strlen(s); i++) { if (s[i] == ' ') continue; if ( strchr(Operator,s[i]) != NULL ) { if (st.empty() || s[i] == '(' || st.top() == '(' ) { st.push(s[i]); } else if (s[i] == '*' || s[i] == '/') { if (st.top() == '+' || st.top() == '-') { st.push(s[i]); } else { num[nc++] = -1; o[oc++] = st.top(); st.pop(); st.push(s[i]); } } else if (s[i] == '+' || s[i] == '-') { while (!st.empty() && st.top() != '(' ) { o[oc++] = st.top(); st.pop(); num[nc++] = -1; } st.push(s[i]); } else //s[i] == ')' { while (!st.empty() && st.top() != '(') { o[oc++] = st.top(); st.pop(); num[nc++] = -1; } st.pop(); // pop ')' } } else { num[nc] = s[i] - '0'; while (i + 1 < strlen(s) && strchr(Operator, s[i+1]) == NULL && s[i+1] != ' ') num[nc] = num[nc] * 10 + (int)(s[++i] - '0'); nc++; } } while (!st.empty()) { { o[oc++] = st.top(); st.pop(); num[nc++] = -1; } } for (int i = 0, j = 0; i < nc; i++) { if (num[i] != -1) cout << num[i]; else cout << o[j++]; } cout << endl; //计算后缀式 bool flag = true; for (int i = 0, j=0; i < nc; i++) { if (num[i] != -1) { sum.push(num[i]); } else { int s1 = sum.top(); sum.pop(); int s2 = sum.top(); sum.pop(); if (o[j] == '+') s1 += s2; else if (o[j] == '-') s1 -= s2; else if (o[j] == '*') s1 *= s2; else { if (s2 == 0) cout << "除数为0!\n"; flag = false; break; s1 /= s2; } j++; sum.push(s1); } } if(flag) cout << sum.top() << endl; }}
0 0
- 栈问题2(四则运算)
- 用栈解决四则运算问题
- 用栈解决四则运算问题
- 四则运算(用栈实现)
- 09_栈的实例2---算术表达式(四则运算)
- 四则运算表达式求值(栈的应用)
- 四则运算表达式求值(栈的应用)
- 四则运算表达式求值(栈的应用)
- 四则运算表达式求值(栈的应用)
- 四则运算表达式求值(栈的应用)
- 用栈实现四则运算表达式(c++)
- 四则运算表达式求值(栈的应用)
- 栈模拟 四则运算 (没写完)
- 四则运算表达式 栈
- 四则运算 c/c++ 栈
- 利用栈 四则运算
- 栈实现四则运算
- 用栈实现四则运算
- 函数之间的相互调用
- “JavaScript Promises和AngularJS $q Service”Part 1 (基础篇)
- test
- 贝叶斯概率
- 1052.Linked List Sorting (25)
- 栈问题2(四则运算)
- 进程创建函数之fork()和vfork()
- shake_wu 的csdn博客开张了!
- script之正则表达式
- 流态区说法-《程序员的职业素养》
- 如何安装WebStorm软件?
- 数组与函数传递
- Task Scheduler 2.0的相关操作
- DIY个人智能家庭网关——硬件篇之433M无线接收解码器(二)