传统弱校HFUT的蒟蒻,真相只有一个

BUPT复试专题—科学计算器(2009)

题目描述

给你一个不带括号的表达式,这个表达式只包含加、减、乘、除,请求出这个表 达式的最后结果,最后结果一定是整数;

输入

一个数学表达式,只包括数字,数字保证是非负整数,以及五种运算符 "+","-","*","/","=";数字和运算符之间有一个或者多个空格,运算符的总数 不会超过 100,最后以"="号结尾,表示表达式结束。注意:使用 C 的同学,在 读取字符串的时候请使用 scanf("%s",..);以免不必要的错误。

输出

整数;

样例输入

1 + 2 + 3 * 6 / 9 =

样例输出

5

来源

 

#include <bits/stdc++.h>
using namespace std;
char donser[100],temp[100];
int change(int num,int from)
{
    int i=from+1,x=0;
    x=temp[from]-'0';
    while(i-from<num)
    {
        x*=10;
        x+=temp[i]-'0';
        i++;
    }
    return x;
}
int main()
{
    memset(donser,0,sizeof(donser));
    memset(temp,0,sizeof(temp));
    while(gets(donser))
    {
        int i=0,j=0;
        while(donser[i]!='\0')
        {
            if(donser[i]!=' ')
                temp[j++]=donser[i];
            i++;
        }
        i=0;
        stack<int> num_stack;
        stack<char> fu_stack;
        while(temp[i]!='\0')
        {
            if(temp[i]>='0'&&temp[i]<='9')
            {
                int num=1,from=i;
                while(temp[i+1]>='0'&&temp[i+1]<='9')
                {
                    num++;
                    i++;
                }
                num_stack.push(change(num,from));
                i++;
            }
            if(!fu_stack.empty())
            {
                if(fu_stack.top()=='*'||fu_stack.top()=='/')
                {
                    int x=num_stack.top();
                    num_stack.pop();
                    int y=num_stack.top();
                    num_stack.pop();
                    if(fu_stack.top()=='*')
                        y=x*y;
                    else y=y/x;
                    num_stack.push(y);
                    fu_stack.pop();
                }
            }
            if(temp[i]=='+'||temp[i]=='-'||temp[i]=='*'||temp[i]=='/')
            {
                fu_stack.push(temp[i]);
                i++;
            }
            if(temp[i]=='=')
            {
                i++;
                continue;
            }
        }
        stack<int> num_stack_temp;
        stack<char> fu_stack_temp;
        while(!fu_stack.empty())
        {
            fu_stack_temp.push(fu_stack.top());
            fu_stack.pop();
        }
        while(!num_stack.empty())
        {
            num_stack_temp.push(num_stack.top());
            num_stack.pop();
        }
        while(!fu_stack_temp.empty())
        {
            int x=num_stack_temp.top();
            num_stack_temp.pop();
            int y=num_stack_temp.top();
            num_stack_temp.pop();
            if(fu_stack_temp.top()=='+')
                y=y+x;
            else
                y=x-y;
            num_stack_temp.push(y);
            fu_stack_temp.pop();
        }
        cout<<num_stack_temp.top()<<endl;
        num_stack_temp.pop();
        memset(donser,0,sizeof(donser));
        memset(temp,0,sizeof(temp));
    }
    return 0;
}

 

posted @ 2018-03-20 10:14  未名亚柳  阅读(171)  评论(0编辑  收藏  举报