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): 11760 Accepted Submission(s): 3811
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
一开始写了半天才想起来运算是有优先级的
想想后缀表达式,这里用两个栈分别记录数值和操作,压入数值前判断栈顶操作,如果是乘法和除法就进行相应计算,否则直接入栈,连续读到两个数值就把栈记录的数据处理并输出,注意当输入"0 + 1"时输出1
#include<cstdio>
#include<iostream>
#include<cstdlib>
#include<algorithm>
#include<ctime>
#include<cctype>
#include<cmath>
#include<string>
#include<cstring>
#include<stack>
#include<queue>
#include<vector>
#include<map>
#define sqr(x) (x)*(x)
#define LL long long
#define INF 0x3f3f3f3f
#define PI 3.14159265358979
#define eps 1e-10
#define mm
using namespace std;
double num[200];//数值
int op[200];//运算符
int fn,rn,fo,ro;//fn,rn num的底和顶,fo ro op的底和顶
double ans;
char s[200];
int main()
{
#ifndef ONLINE_JUDGE
freopen("t","r",stdin);
#endif
bool flag=false;
fn=fo=0;
rn=-1;
ro=0;
op[0]=1;
while (~scanf("%s",s))
{
if (flag && isdigit(s[0]))
{
ans=0;
while (fn<=rn)
{
if (op[fn]==1)
ans+=num[fn];
else
ans-=num[fn];
fn++;
}
printf("%.2f\n",ans);
fn=fo=0;
rn=-1;
ro=0;
flag=false;
}
/*
if (s[0]=='0' && s[1]=='\0')
break;
*/
if (isdigit(s[0]))
{
flag=true;
if (op[ro]==3)
{
num[rn]*=atoi(s);
ro--;
continue;
}
if (op[ro]==4)
{
num[rn]/=atoi(s);
ro--;
continue;
}
num[++rn]=atoi(s);
continue;
}
flag=false;
switch (s[0])
{
case '+':op[++ro]=1;break;
case '-':op[++ro]=2;break;
case '*':op[++ro]=3;break;
case '/':op[++ro]=4;break;
}
}
return 0;
}