2006浙大:简单计算器
2016-05-16 23:55
211 查看
题目描述:
读入一个只包含 +, -, *, / 的非负整数计算表达式,计算该表达式的值。
输入:
测试输入包含若干测试用例,每个测试用例占一行,每行不超过200个字符,整数和运算符之间用一个空格分隔。没有非法表达式。当一行中只有0时输入结束,相应的结果不要输出。
输出:
对每个测试用例输出1行,即该表达式的值,精确到小数点后2位。
样例输入:
样例输出:
读入一个只包含 +, -, *, / 的非负整数计算表达式,计算该表达式的值。
输入:
测试输入包含若干测试用例,每个测试用例占一行,每行不超过200个字符,整数和运算符之间用一个空格分隔。没有非法表达式。当一行中只有0时输入结束,相应的结果不要输出。
输出:
对每个测试用例输出1行,即该表达式的值,精确到小数点后2位。
样例输入:
1 + 2 4 + 2 * 5 - 7 / 11 0
样例输出:
3.00 13.36
#include <cstdio> #include <cstring> #include <algorithm> #include <stack> using namespace std; const int MAXN=1005; char s[MAXN]; bool isOp(char op) { if(op=='+'||op=='-'||op=='*'||op=='/') return true; else return false; } int Priority(char op) { switch(op) { case '+':return 1; case '-':return 1; case '*':return 2; case '/':return 2; } } double cal(double x,double y,char op) { switch(op) { case '+':return x+y; case '-':return x-y; case '*':return x*y; case '/':return x/y; } } char ss[MAXN]; int top; int main() { while(gets(s)&&strcmp(s,"0")!=0) { top=0; stack<char> op; stack<double> it; int len=strlen(s); for(int i=0;i<len;i++) { if(s[i]==' ') continue; ss[top++]=s[i]; } int e=0; for(int i=0;i<top;i++) { if(isOp(ss[i])) { it.push(double(e)); e=0; if(op.empty()) { op.push(ss[i]); } else { int pri1=Priority(ss[i]); int pri2=Priority(op.top()); if(pri1>pri2) { op.push(ss[i]); } else { do{ double x=it.top();it.pop(); double y=it.top();it.pop(); double res=cal(y,x,op.top()); op.pop(); it.push(res); }while(!op.empty()&&pri1<=Priority(op.top())); op.push(ss[i]); } } } else { e*=10; e=e+ss[i]-'0'; } } it.push(double(e)); while(it.size()>1) { double x=it.top();it.pop(); double y=it.top();it.pop(); double res=cal(y,x,op.top());op.pop(); it.push(res); } double res=it.top(); printf("%.2lf\n",res); } return 0; }
相关文章推荐
- httpd
- 企业证书发布笔记
- 密码学的起源与基本概念
- Android多媒体--SoundPool
- HDU 2135 Rolling table(方阵旋转+找规律)
- 城市线程练习题后续
- 关于char 指针变量char *=p;这个语句的输出问题
- bat 命令行
- mysql int,bigint,smallint和tinyint理解
- 君子一诺(爱情故事)
- 基于树莓派raspberry: 移植 2.4寸TFT显示屏以及源码分析
- RecyclerView基本使用方式
- diff和patch命令(1)
- Jersey 2.22.2 官方文档第3章学习笔记
- http协议初体验
- MYSQL基本操作
- sql基础常用函数总结
- 找不到#include "stdafx.h"解决办法
- Handler消息机制分析
- Glib学习(8) 动态字节数组 Byte Arrays