中缀转后缀同时求值
2016-03-19 23:04
344 查看
中缀转后缀的同时进行求值
边转换边求值,一趟完成
边转换边求值,一趟完成
#include<iostream> #include<stack> #include<string> using namespace std; //中缀转后缀并求值,只有加减乘除,输入形如:12.7-2*(72.2+4*(2.2+2.8))/2+100# int isp(char ks){ if(ks=='-'||ks=='+') return 2; else if(ks=='*'||ks=='/') return 4; else return 0; } int icp(char ks){ if(ks=='-'||ks=='+') return 1; else if(ks=='*'||ks=='/') return 3; else return 5; } void calculate(stack<double>& nStack,char c){ double dou2=nStack.top(); nStack.pop(); double dou1=nStack.top(); nStack.pop(); if(c=='-'){ nStack.push(dou1-dou2); } if(c=='+'){ nStack.push(dou1+dou2); } if(c=='*'){ nStack.push(dou1*dou2); } if(c=='/'){ nStack.push(dou1/dou2); } } void solve () { char ch, y ; stack <char> s ; stack <double> operandStack ; string operandStr; double operand; bool construcOperand=false; s.push ('#'); while (cin.get ( ch ) , ch != '#') { if (isdigit ( ch )||ch=='.') { if(construcOperand==false){ cout<<" "; construcOperand=true; } operandStr+=ch; cout << ch; } else{ if(construcOperand==true){ operand=atof(operandStr.c_str()); operandStack.push(operand); construcOperand=false; operandStr=""; } if (ch ==')') for (y=s.top(),s.pop(); y!= '('; y=s.top( ),s.pop()){ cout <<" "<< y ; calculate(operandStack,y); } else { for (y =s.top(),s.pop(); isp (y) > icp (ch); y=s.top(),s.pop()){ cout<<" "<<y ; calculate(operandStack,y); } s.push (y) ; s.push (ch); } } } if(construcOperand==true){ operand=atof(operandStr.c_str()); operandStack.push(operand); construcOperand=false; operandStr=""; } while (!s.empty()&&s.top()!='#') { y = s.top();s.pop() ; cout <<" "<<y ; calculate(operandStack,y); } cout<<endl<<"计算结果是: "<<operandStack.top()<<endl; } int main(){ solve (); }
相关文章推荐
- Mysql中各种常见数据库存储引擎对比
- 【转】VMware 11安装Mac OS X 10.10 及安装Mac Vmware Tools.
- 积累的一些Java编程需要注意的性能考虑
- 积累的一些Java编程需要注意的性能考虑
- C++ typeid实现原理
- 【2016/3】C++ 类与对象进阶 运算符重载 new delete 模板 继承
- DOM操纵样式表
- (边写边更)用PHP简单的学生个人信息记录程序
- 图像处理之双边滤波介绍与源码实现
- linux学习一天一个命令(22)[which命令]
- input dump
- 关于type_info总结
- Windows手工创建服务方法
- Spring Data之春D(1)
- 并查集基础
- 【Android开发】微信精选,文章资讯类App开发记录总结
- jar命令的用法
- Codeforces 653A Bear and Three Balls【水题】
- Android开发不完整规范
- Codeforces 653A Bear and Three Balls【水题】