csu1506: ZZ的计算器

好吧, 这道题绕了好久,之前用int, 用 double, 最后才发现是long  long 啊 而且string.h 头文件也没加 。。。。。

 

//http://acmore.net/problem.php?cid=1015&pid=3
#include <iostream>
#include <stdio.h>
#include <string>
#include <string.h>
#include <stack>
using namespace std;

stack<long long> stk;
stack<char> op;

int main()
{
    char str[100];
    bool bl ;
    int len, i, j, k;
    long long a, b;
    while (scanf("%s",str)!=EOF)
    {
        bl = true;
        while (!stk.empty())
            stk.pop();
        while (!op.empty())
            op.pop();
        i = 0;
        if (str[0] == '-')
            i++;
        len = strlen(str);
        for(; i<len; i++)
        {
            a = str[i++]-'0';
            while(i < len && str[i] >='0' && str[i] <='9')
            {
                a *= 10;
                a += str[i++] -'0';
            }
            if (!op.empty())
            {
                if (op.top() == '*')
                {
                    b = stk.top();
                    stk.pop();
                    a *=b;
                    op.pop();
                }
                else if (op.top() == '/')
                {
                    b = stk.top();
                    stk.pop();
                    if (a == 0)
                    {
                        puts("impossible");
                        bl = false;
                        break;
                    }
                    a = b / a;
                    op.pop();
                }
            }
            stk.push(a);
            if (i < len)
                op.push( str[i]);
        }
        if (!bl)
            continue;
        long long sum=0;
        while (!op.empty())
        {
            a = stk.top();
            stk.pop();
            if (op.top() == '+')
            {
                sum += a;
                op.pop();
            }
            else 
            {
                sum -= a;
                op.pop();
            }
        }
        
        if (str[0] == '-')
            sum -= stk.top();
        else sum += stk.top();
        printf("%lld\n", sum);

    }
    return 0;
}

 

posted @ 2013-04-29 11:05  旅行的蜗牛  阅读(204)  评论(0编辑  收藏  举报