表达式求值
来源:互联网 发布:桌面笔记软件 编辑:程序博客网 时间:2024/05/22 07:52
题目描述
利用栈来实现含有加,减,乘,除等基本运算,输出表达式的值
输入
3*(15/5)+8=
输出
17
样例输入
24-(6+(27/3)*2)=
样例输出
0
AC代码:
#include<cstdio>#include<cstring>#include<stack>using namespace std;int main(){int T,i,len; int x,y,flat; char str[100]; stack<int>n; stack<char>c; scanf("%s",str); len=strlen(str); for(i=0;i<len;){ if(str[i]>='0'&&str[i]<='9'){ flat=0; while(str[i]>='0'&&str[i]<='9'){ flat=flat*10+str[i]-'0'; i++; } n.push(flat); } else if(str[i]=='('){ c.push(str[i]); i++; } else if(str[i]=='+'||str[i]=='-'){ if(!c.empty()&&c.top()!='('){ x=n.top(); n.pop(); y=n.top(); n.pop(); if(c.top()=='+')n.push(x+y); else if(c.top()=='-')n.push(y-x); else if(c.top()=='*')n.push(x*y); else if(c.top()=='/')n.push(y/x); c.pop(); } else{ c.push(str[i]); i++; } } else if(str[i]=='*'||str[i]=='/'){ if(!c.empty()&&c.top()!='('){ if(c.top()=='+'||c.top()=='-'){ c.push(str[i]); i++;continue; } else{ x=n.top(); n.pop(); y=n.top(); n.pop(); if(c.top()=='*')n.push(x*y); else n.push(y/x); c.pop(); } } else{ c.push(str[i]); i++; } } else if(str[i]==')'){ while(c.top()!='(') { x=n.top(); n.pop(); y=n.top(); n.pop(); if(c.top()=='-') n.push(y-x); else if(c.top()=='+') n.push(x+y); else if(c.top()=='*') n.push(x*y); else n.push(y/x); c.pop(); } c.pop(); i++; } else if(str[i]=='=') { if(!c.empty()) { while(!c.empty()) { x=n.top(); n.pop(); y=n.top(); n.pop(); if(c.top()=='-'){ n.push(y-x); i++; } else if(c.top()=='+'){ n.push(x+y); i++; } else if(c.top()=='*'){ n.push(x*y); i++; } else if(c.top()=='/'){ n.push(y/x); i++; } c.pop(); } } else i++; } } printf("%d\n",n.top()); n.empty(); c.empty(); return 0;}
0 0
- 表达式求值
- 表达式求值
- 表达式求值
- 表达式求值
- 表达式求值
- 表达式求值
- 表达式求值
- 表达式求值
- 表达式求值
- 表达式求值
- 表达式求值
- 表达式求值
- 表达式求值
- 表达式求值
- 表达式求值
- 表达式求值
- 表达式求值
- 表达式求值
- is running beyond virtual memory limits
- ffmpeg的时间戳
- 读书笔记——鸟哥(01)磁盘分区
- Android中的消息机制
- 网易互娱2017实习生招聘在线笔试第一场-电子数字
- 表达式求值
- 方法的直接调用,反射调用与……Lambda表达式调用
- Combination Sum | && || Leetcode
- POJ 3345 Bribing FIPA(树形dp+背包)
- Android生命周期学习笔记
- Python调用SIFT出现的问题:No such file or directory: '*.sift' 解决办法,超好用
- NVIDIA显卡驱动未加载问题——未完全解决
- Java 学习笔记(一)
- tinyxml源代码解析(一)