算术表达式
2016-03-15 21:58
211 查看
题目描述:
读入一个只包含 +, -, *, / 的非负整数计算表达式,计算该表达式的值。
输入:
测试输入包含若干测试用例,每个测试用例占一行,每行不超过200个字符,整数和运算符之间用一个空格分隔。没有非法表达式。当一行中只有0时输入结束,相应的结果不要输出。
输出:
对每个测试用例输出1行,即该表达式的值,精确到小数点后2位。
样例输入:
样例输出:
思路:
栈,后缀表达式。
中缀表达式->后缀表达式:栈中的操作符从栈顶到栈底 严格递减(即保证push到符号栈的符号必然比栈顶符号优先级高,否则pop)
读入一个只包含 +, -, *, / 的非负整数计算表达式,计算该表达式的值。
输入:
测试输入包含若干测试用例,每个测试用例占一行,每行不超过200个字符,整数和运算符之间用一个空格分隔。没有非法表达式。当一行中只有0时输入结束,相应的结果不要输出。
输出:
对每个测试用例输出1行,即该表达式的值,精确到小数点后2位。
样例输入:
1 + 2 4 + 2 * 5 - 7 / 11 0
样例输出:
3.00 13.36
思路:
栈,后缀表达式。
中缀表达式->后缀表达式:栈中的操作符从栈顶到栈底 严格递减(即保证push到符号栈的符号必然比栈顶符号优先级高,否则pop)
#include "iostream" #include "stdio.h" #include "math.h" #include "vector" #include "stack" #include "queue" #include "memory.h" #include "algorithm" #include "string" using namespace std; char e[250],post[250]; stack<char>Op; bool Isnum(char c) { if(c>='0'&&c<='9') return true; return false; } int OPMode(char c) { if(c=='+') return 1; if(c=='-') return 2; if(c=='*') return 3; if(c=='/') return 4; return -1; } void SplitExp(char* s) { int i,j=0; memset(post,'\0',sizeof(post)); for(i=0;i<strlen(s);i++) { if(s[i]==' ') continue; post[j++]=' '; while(Isnum(s[i])) post[j++]=s[i++]; int curop=OPMode(s[i]); if(curop!=-1) { if(curop<=2) while(!Op.empty()) { post[j++]=Op.top(); Op.pop(); } else { while(!Op.empty()&&OPMode(Op.top())>2) { post[j++]=Op.top(); Op.pop(); } } Op.push(s[i]) ; } } while(!Op.empty()) { post[j++]=Op.top(); Op.pop(); } } stack<double>Num; double Cal() { while(!Num.empty()) Num.pop(); int i=0,j; int len=strlen(post); while (i++<len) { if(post[i]==' ') continue; double cur=0; bool hasnum=false; while (Isnum(post[i])) { cur*=10; cur+=post[i++]-'0'; hasnum=true; } if(hasnum) Num.push(cur); if(OPMode(post[i])!=-1) { double num1=Num.top(); Num.pop(); double num2=Num.top(); Num.pop(); switch(post[i]) { case '+': Num.push(num2+num1);break; case '-': Num.push(num2-num1);break; case '*': Num.push(num2*num1);break; case '/': Num.push(num2/num1);break; } } } return Num.top(); } int main() { while(gets(e)) { if(strcmp(e,"0")==0) break; SplitExp(e); printf("%.2f\n",Cal()); } }
相关文章推荐
- JS定时器_setInterval
- iOS推送原理和证书生成简介
- 智能指针 与 oc中的指针
- IIS 8 下使用 WCF
- c++与c不太相同的一些地方1
- 排序算法——快速排序
- 路由协议RIP、EIGRP、OSPF
- 路由协议RIP、EIGRP、OSPF
- struts2——(7)(①result常用结果类型(dispatcher,redirect,redirectAction)②全局result)
- Cocos2d-x 3.1.1 学习日志4--cocos2d-x解决中文乱码问题的几种办法
- JS定时器_setTimeout
- Android自定义控件模仿iOS滑块SwitchButton
- hdu3613 extend-kmp(Trie入门)
- Java处理异常原则
- 开通博客,纪念一下
- 阿里移动安全2015年第二季度报告
- dorado7的学习3月15
- 冒泡排序、选择排序和插入排序--由小到大,,由大到小
- poj2352+2481 stars+cows 树状数组
- Parcelable 序列化和反序列化