逆波兰计算器
来源:互联网 发布:优化语文教学五环节 编辑:程序博客网 时间:2024/06/09 23:47
#include<iostream>#include<algorithm>#include<stack> #include<string>using namespace std;int level(char ch);int main(){ stack <char> s1, s2, s3, s4; // char str[10]; int p1, p2; cin>>str; char ch; for(int i = 0;str[i]!='\0';i++) { if(str[i] >='0' && str[i]<='9') { s1.push(str[i]); } if(str[i] == '(') { s2.push(str[i]);//左括号放入运算符堆栈 } else if(str[i]== ')') { while(s2.top() != '(') { ch = s2.top(); s2.pop(); s1.push(ch); } s2.pop(); } else if(str[i] == '+' || str[i] == '-' || str[i] == '*' || str[i] == '/') { if(s2.empty()) { s2.push(str[i]); } else if(!s2.empty() && s2.top() == '(' || s2.top() == ')') { s2.push(str[i]); } else if(!s2.empty() && level(str[i]) > level(s2.top())) { s2.push(str[i]); } else if(!s2.empty() && level(str[i]) <= level(s2.top())) { ch = s2.top(); s2.pop(); s1.push(ch); s2.push(str[i]); } } } while(!s2.empty()) { ch = s2.top(); s2.pop(); s1.push(ch); }//s1 从左到又数逆波兰 cout<<endl; cout<<"逆波兰从右往左看"<<endl; while(!s1.empty()) { ch = s1.top(); cout<<ch<<' '; s3.push(ch); s1.pop(); } cout<<endl; /*while(!s3.empty()) { cout<<s3.top()<<' '; s3.pop(); }*/ while(!s3.empty()) { if(s3.top() >= '0' && s3.top() <= '9') { s4.push(s3.top()); s3.pop(); } else if(s3.top() == '+' || s3.top() == '-' || s3.top() == '*' || s3.top() == '/') { if(s3.top() == '+') {s3.pop(); p1 = s4.top() - '0'; s4.pop(); p2 = s4.top() - '0'; s4.pop(); if(s3.empty()) { cout<<p1+p2<<endl; } else { s4.push(char(p1+p2+48)); } } else if(s3.top() == '-') {s3.pop(); p1 = s4.top() - '0'; s4.pop(); p2 = s4.top() - '0'; s4.pop(); if(s3.empty()) { cout<<p2-p1<<endl; } else { s4.push(char(p2-p1+48)); } } else if(s3.top() == '*') {s3.pop(); p1 = s4.top() - '0'; s4.pop(); p2 = s4.top() - '0'; s4.pop(); if(s3.empty()) { cout<<p1*p2<<endl; } else { s4.push(char(p1*p2+48)); } } else if(s3.top() == '/') { s3.pop(); p1 = s4.top() - '0'; s4.pop(); p2 = s4.top() - '0'; s4.pop(); if(s3.empty()) { cout<<p2/p1<<endl; } else { s4.push(char(p2/p1+48)); } } } } return 0;} int level(char ch) //优先级判断 { if(ch=='(') return 0; if(ch=='+'||ch=='-') return 1; if (ch=='*'||ch=='/') return 2; }
阅读全文
0 0
- 逆波兰计算器
- 计算器 | 逆波兰表达式
- 逆波兰实现计算器
- 简单逆波兰计算器
- 逆波兰计算器
- 逆波兰表达式计算器
- 逆波兰计算器
- 逆波兰计算器
- 逆波兰计算器
- 逆波兰计算器:
- 逆波兰计算器
- 逆波兰计算器
- 逆波兰计算器
- java 实现逆波兰计算器
- 逆波兰表示法计算器
- 计算器之逆波兰算法
- 逆波兰计算器改进版
- 简单计算器-逆波兰式
- BeautifulSoup
- 把文本文件中的数据读取到集合
- Virus_VBS_SampleAnalysis_1
- 思路
- 删除某一个节点k的方法(1320 P103)
- 逆波兰计算器
- 包装类
- 泛型基本使用
- pandas中时间序列——date_range函数
- linux top命令
- PHP 中字符编码转换 iconv() 和 mb_convert_encoding() 的区别
- 用于语义分割的全卷积网络 (fully convolutional networks for semantic segmentation)
- 堆棋子
- 我的划时代意义的递归题--Sudoku Killer