nsoj 4647 表达式求值
来源:互联网 发布:生成雪碧图 for mac 编辑:程序博客网 时间:2024/05/22 16:39
题目链接
要写数据结构作业,之前写过这个,
今天又从新写了一遍。
主要是用栈,
两个栈,一个存数,一个存运算符,
根据运算符的优先级写一个判断函数。
然后把表达式从左至右一次存进去,
遇见优先级高的直接计算,
遇见括号内的直接计算
之后再把栈倒着读出来依次计算
#include<bits/stdc++.h>using namespace std;int judge(char c){ if(c=='=') return 0; if(c=='+'||c=='-') return 1; if(c=='*'||c=='/') return 2; return 0;}void calculator(stack <double> &num,stack <char> &op){ double n1=num.top(); num.pop(); double n2=num.top(); num.pop(); switch(op.top()){ case'+': num.push(n2+n1);break; case'-': num.push(n2-n1);break; case'*': num.push(n2*n1);break; case'/': num.push(n2/n1);break; } op.pop();}int main(){ char a[1000];//假设表达式长度小于1000 stack< char > op; stack< double > num; while(~scanf("%s",a)){ double x,y,ans; int len=strlen(a); for(int i=0;i<len;i++){ if(isdigit(a[i])){//printf("%d\n",i); double n=0;//=a[i]-'0'; bool f=1; double t2=0.1; while(isdigit(a[i])||a[i]=='.'){ if(a[i]=='.'){ f=0;i++;continue; } if(f){ n=n*10+a[i]-'0'; }else{ n=n+(a[i]-'0')*t2; t2/=10; } i++; }i--;num.push(n);//printf("4\n"); }else{ if(a[i]=='('){ op.push(a[i]); }else if(a[i]==')'){ while(op.top()!='(') calculator(num,op);//printf("000\n"); op.pop(); }else if(op.empty()||judge(a[i])>judge(op.top())){ op.push(a[i]);//printf("111\n"); }else {//printf("2222\n"); while(!op.empty()&&judge(a[i])<=judge(op.top())) calculator(num,op); op.push(a[i]); } } //printf("%.2f\n",num.top()); } op.pop(); printf("%.2f\n",num.top()); num.pop(); } return 0;}
0 0
- nsoj 4647 表达式求值
- NSOJ
- 表达式求值
- 表达式求值
- 表达式求值
- 表达式求值
- 表达式求值
- 表达式求值
- 表达式求值
- 表达式求值
- 表达式求值
- 表达式求值
- 表达式求值
- 表达式求值
- 表达式求值
- 表达式求值
- 表达式求值
- 表达式求值
- 文件I/O
- 理解java的CompletionService
- 441. Arranging Coins
- POJ 2431 Expedition 优先队列+贪心
- 父母赴美签证办理
- nsoj 4647 表达式求值
- JavaScript对象数组的处理
- hdu 1016(dfs基础)
- PE 66 Diophantine equation(Pell方程)
- 硬盘分区小知识
- MySQL源码详解一 mysqld启动
- Vijos P1053 Easy sssp(SPFA 判负环)
- Android性能优化学习(三)常见内存泄漏分析
- 第十二周项目2---操作用邻接表存储的图