题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1237
简单计算器
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 + 2 4 + 2 * 5 - 7 / 11 0
Sample Output
3.00 13.36
Source
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;
}