HDU 1237 简单计算器 && 字符串模拟四则运算

作者按:本来是心情不好,想秒几道水题舒缓一下心情。可是没想到这道题好烦呀,居然让我推到重写了一次。。。

解法:每次处理一串 * 和 /  ,遇到 + 或 - 就更新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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值