表达式求值 【栈的应用 或 二叉树的应用
来源:互联网 发布:长河古典抗菌喷剂淘宝 编辑:程序博客网 时间:2024/05/09 20:27
#include <iostream>#include <string>#include <stack>#include <fstream>using namespace std;bool isone(char c){return (c=='+' || c=='-');}bool istwo(char c){return (c=='*' || c=='/');}string shorten(string m){stack<char> s;string sur;int i;char w;sur;for(i=0;i<m.size();i++){if(isdigit(m[i]) || m[i]=='.'){while(isdigit(m[i]) || m[i]=='.')sur += m[i++];i--;sur += '$';}else if(isone(m[i])){while(s.size() && (isone(s.top()) || istwo(s.top()))){sur+=s.top();s.pop();}s.push(m[i]);}else if(m[i]==')'){while(s.top()!='('){sur+=s.top();s.pop();}s.pop();}else if(istwo(m[i])){while(s.size() && istwo(s.top())){sur+=s.top();s.pop();}s.push(m[i]);}else s.push(m[i]);}while(s.size()){sur+=s.top();s.pop();}return sur;}double tentimes(int n){double res=1;for(int i=0;i<n;i++){res *= 10;}return res;}double str2double(string s){double res=0;char c;int dec=0;for(int i=1;i<=s.size();i++){c=s[i-1];if(c=='.') dec=i;else if(!dec) res = res*10 + c-'0';else res += (c-'0')/tentimes(i-dec);}return res;}double calculate(string s){double res, t;stack<double> num;string temp;int i;for(i=0;i<s.size();i++){temp="";if(isdigit(s[i]) || s[i]=='.'){while(isdigit(s[i]) || s[i]=='.') temp+=s[i++];//如果最后一位是数字,这样做会出错 num.push(str2double(temp));}else{switch (s[i]){case '+': t=num.top(); num.pop(); t+=num.top();num.pop();num.push(t);break;case '-': t=num.top(); num.pop(); t=num.top()-t;num.pop();num.push(t);break;case '*': t=num.top(); num.pop(); t*=num.top();num.pop();num.push(t);break;case '/': t=num.top(); num.pop(); t=num.top()/t;num.pop();num.push(t);break;default: cerr << "Fatal Error! Result would be wrong!" << endl; system("pause");break;}}}res=num.top();return res;}int main(){string mid, sur;cout << "please input:";cin >> mid;sur = shorten(mid);cout << "successfully executed! The right hand operator expression is: ";cout << sur << endl;cout << "The result is: " <<calculate(sur) << endl;return 0;}
1 0
- 表达式求值 【栈的应用 或 二叉树的应用
- 栈的应用 表达式求值
- 表达式求值【栈的应用】
- 栈的应用表达式求值
- 栈的应用-表达式求值
- 栈的应用 表达式求值
- 栈的应用-四则运算表达式的求值
- 栈的一个应用表达式求值
- 栈的应用--算术表达式求值
- 表达式求值(栈的应用)(C++)
- 栈的应用——表达式求值
- 数据结构 栈的应用-- 表达式求值
- 四则运算表达式求值(栈的应用)
- NYOJ 35 表达式求值【栈的应用】
- 表达式求值——栈的应用
- 【数据结构】栈的应用 I :表达式求值
- 四则运算表达式求值(栈的应用)
- 栈的应用之表达式求值code_legend
- #笔记#圣思园 JavaWeb 第18讲——forward元素,session和request向导式注册,请求转发、重定向
- 复杂链表的复制
- python-random模块
- JavaScript权威指南_116_第15章_脚本化文档_15.2-选取文档元素-通过CSS类选取元素
- 设置取消缓存
- 表达式求值 【栈的应用 或 二叉树的应用
- 终于完成几个淘宝采集相关产品(http://www.9zhai.net/)
- 看过的博客文章汇总
- 黑马程序员---反射总结笔记(2015.7.1)
- U盘安装Windows和Ubuntu 15.04双系统图解教程
- vs2010打开时出现Vmdebugger未能加载或出现了异常是否移除该外接程序??
- Binary Tree Level Order Traversal II
- Access restriction: The type Resource is not accessible due to restriction on required library
- 基于thinkphp实现根据用户ip判断地理位置并提供对应天气信息的应用