作者按:本来是心情不好,想秒几道水题舒缓一下心情。可是没想到这道题好烦呀,居然让我推到重写了一次。。。
解法:每次处理一串 * 和 / ,遇到 + 或 - 就更新last值,如此往复。不过第一串需要特殊算一下。幸好没有括号。。。
代码:
#include <iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<map>
#include<queue>
#include<cmath>
#include<vector>
#define inf 0x3f3f3f3f
#define Inf 0x3FFFFFFFFFFFFFFFLL
#define pi acos(-1.0)
#define eps 1e-8
using namespace std;
const int maxn = 100010;
int sum = 0;
int top = -2;
char s[maxn];
int n;
int next()
{
top += 2;
if(s[top]<='9'&&s[top]>='0')
{
int now = top; int sum = 0;
while(s[now]!=' ' && now < n)
{
sum*=10;
sum += s[now] - '0';
now ++;
}
top = now - 1;
return sum;
}
return s[top];
}
double last = 0;
int fun()
{
int a, b; char c, d;
while(top<n-1)
{
d = next();
double tmp = next();
while(true)
{
if(top==n-1) break;
c = next();
if(c=='+'||c=='-')
{
top-=2;
break;
}
a = next();
if(c=='*') tmp*=a;
else tmp/=a;
}
if(d=='+')
last += tmp;
else
last -= tmp;
}
}
int main()
{
//freopen("in.txt","r",stdin);
while( gets(s))
{
top = -2;
if(strlen(s)==1 && s[0] == '0') break;
last = 0;
n = strlen(s);
double tmp = next();
char c; int a;
while(true)
{
if(top==n-1) break;
c = next();
if(c=='+'||c=='-')
{
top-=2;
break;
}
a = next();
if(c=='*') tmp*=a;
else tmp/=a;
}
last += tmp;
fun();
printf("%.2lf\n",last);
}
return 0;
}