HDU 1237 简单计算器
2016-07-19 02:30
330 查看
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1237
Total Submission(s): 17885 Accepted Submission(s): 6280
4 + 2 * 5 - 7 / 11
0
13.36
思路:STL的stack。因为题目保证输入合法,且只含有空格,+,-,*,/,数字,所以只要遇到*或者/时,将结果放入栈,那么最后就只剩下+和-,就很好处理了。详见代码。
附上AC代码:
简单计算器
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 17885 Accepted Submission(s): 6280
Problem Description
读入一个只包含 +, -, *, / 的非负整数计算表达式,计算该表达式的值。Input
测试输入包含若干测试用例,每个测试用例占一行,每行不超过200个字符,整数和运算符之间用一个空格分隔。没有非法表达式。当一行中只有0时输入结束,相应的结果不要输出。Output
对每个测试用例输出1行,即该表达式的值,精确到小数点后2位。Sample Input
1 + 24 + 2 * 5 - 7 / 11
0
Sample Output
3.0013.36
Source
浙大计算机研究生复试上机考试-2006年Recommend
JGShining思路:STL的stack。因为题目保证输入合法,且只含有空格,+,-,*,/,数字,所以只要遇到*或者/时,将结果放入栈,那么最后就只剩下+和-,就很好处理了。详见代码。
附上AC代码:
#include <bits/stdc++.h> //#pragma comment(linker, "/STACK:102400000, 102400000") using namespace std; const int maxn = 205; char str[maxn]; stack<double> num, numb; stack<char> op, opt; int main(){ #ifdef LOCAL freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif while (gets(str) && strcmp(str, "0")){ while (!numb.empty()) numb.pop(); int len = strlen(str); for (int i=0; i<len; ++i){ if (str[i] == ' ') continue; if (str[i]=='*' || str[i]=='/'){ double y=0.0, x=num.top(); num.pop(); char t = str[i]; for (i+=2; i<len; ++i){ if (str[i] != ' ') y = y*10+str[i]-'0'; else break; } num.push(t=='*' ? x*y : x/y); } else if (str[i]=='+' || str[i]=='-') op.push(str[i]); else{ double t = 0.0; for (; i<len; ++i){ if (str[i] != ' ') t = t*10+str[i]-'0'; else break; } num.push(t); } } while (!num.empty()){ numb.push(num.top()); num.pop(); } while (!op.empty()){ opt.push(op.top()); op.pop(); } while (!numb.empty() && !opt.empty()){ double x = numb.top(); numb.pop(); double y = numb.top(); numb.pop(); char t = opt.top(); opt.pop(); numb.push(t=='+' ? x+y : x-y); } printf("%.2f\n", numb.top()); } return 0; }
相关文章推荐
- 浅析STL中的常用算法
- STL区间成员函数及区间算法总结
- c++ STL容器总结之:vertor与list的应用
- C++在成员函数中使用STL的find_if函数实例
- 关于STL中list容器的一些总结
- Mysql Error Code : 1436 Thread stack overrun
- 关于STL中的map容器的一些总结
- 基于java中stack与heap的区别,java中的垃圾回收机制的相关介绍
- 浅析stl序列容器(map和set)的仿函数排序
- STL list链表的用法详细解析
- stl容器set,map,vector之erase用法与返回值详细解析
- STl中的排序算法详细解析
- 关于STL中vector容器的一些总结
- 关于STL中set容器的一些总结
- 简单说说STL的内存管理
- Python算法之栈(stack)的实现
- STL与泛型编程(1)---模板
- Stack数据结构的特点后进先出的应用:大数据运算
- C 堆栈,运行时类型挷定
- jstack和线程dump分析