逆波兰实现计算器
2014-03-22 20:46
183 查看
#include <iostream> #include <stack> #include <string> using namespace std; bool isopretor(char ch) { switch(ch) { case '+' : case '-': case '*': case '/': case '%': return 1; default: return -1; } } int priority(char ch) { switch(ch) { case '*': case '/': case '%': return 2; case '(': return 0; case '+': case '-': return 1; case '#': return -1; default: return -1; } } void postfix(string &pre,char post[],int &len) { int i=0,j=0; stack<char>mystack; mystack.push('#'); while (pre[i]!='#') { if (pre[i]=='(') { mystack.push(pre[i]); }else if ( (pre[i]>='0' && pre[i]<='9')||pre[i]== '.') { post[j++]=pre[i]; } else if (pre[i]==')') { while(mystack.top()!='(') { post[j++]=mystack.top(); mystack.pop(); } mystack.pop(); } else if (isopretor(pre[i])) { post[j++]=' '; while(priority(pre[i])<=priority(mystack.top())) { post[j++]=mystack.top(); mystack.pop(); } mystack.push(pre[i]); } i++; } while (mystack.top()!='#')//模板类stack top方法报错当没有元素时 { post[j++]=mystack.top(); mystack.pop(); } post[j]='#'; len=j; } //把字符串数据转为数字存下来 double read_num(char *post,int &i) { double sum=0; while (post[i]>='0'&&post[i]<='9') { sum=sum*10+post[i]-'0'; i++; } int k=0; if (post[i]=='.') { i++; while (post[i]>='0'&&post[i]<='9') { sum=sum*10+post[i]-'0'; i++;k++; } } if (k!=0) { sum/=pow(10.0,k); } return sum; } //计算逆波兰的值 double postValue(char *post) { stack<double>mystack; double x1,x2; int i=0; while (post[i]!='#') { if (post[i]>='0'&&post[i]<='9') { mystack.push(read_num(post,i)); } else if (post[i]==' ') { i++; } else if (post[i]=='+') { x2=mystack.top(); mystack.pop(); x1=mystack.top(); mystack.pop(); mystack.push(x1+x2); i++; } else if (post[i]=='-') { x2=mystack.top(); mystack.pop(); x1=mystack.top(); mystack.pop(); mystack.push(x1-x2); i++; } else if (post[i]=='*') { x2=mystack.top(); mystack.pop(); x1=mystack.top(); mystack.pop(); mystack.push(x1*x2); i++; } else if (post[i]=='/') { x2=mystack.top(); mystack.pop(); x1=mystack.top(); mystack.pop(); mystack.push(x1/x2); i++; } else if (post[i]=='%') { x2=mystack.top(); mystack.pop(); x1=mystack.top(); mystack.pop(); mystack.push((int)x1%(int)x2); i++; } } return mystack.top(); } int main() { string pre="(2+4)*5+(5-2)/2#"; char post[100]; int len=0; postfix(pre,post,len);//转成逆波兰 for (int i=0;i<len;i++) { cout<<post[i]; } cout<<endl; cout<<postValue(post)<<endl; }
相关文章推荐
- MFC计算器 用vector实现和计算逆波兰表达式
- 逆波兰表达式实现计算器(附c++代码)
- c# 逆波兰式实现计算器
- 逆波兰 计算器 C语言实现
- 利用栈实现计算器,先转换为逆波兰式之后运算
- 一个逆波兰表达式实现的四则混合运算计算器
- 栈_逆波兰表达式_计算器实现_Golang版本
- 逆波兰 计算器 C语言实现代码
- 逆波兰计算器的实现
- 怎么实现Linux下的逆波兰计算器dc?
- 分享一个Swift语言的逆波兰表达式计算器的实现
- 【晨哥的C语言之旅】逆波兰表达式实现计算器功能
- K&R---函数与程序结构中,逆波兰计算器的实现
- 基于逆波兰RPN算法的计算器实现
- 逆波兰算法,实现一个四则运算计算器
- 用HTML、CSS、JavaScript 实现一个简单的计算器
- 作业:C++利用栈实现的计算器
- 复杂版计算器的实现
- Python实现计算器功能
- 【原创】Delphi实现数学表达式的计算(逆波兰式法)-四则运算解析