计算器2

给你一个不带括号的表达式,这个表达式只包含加、减、乘、除,请求出这个表达式的最后结果,最后结果一定是整数(不是原题,不过就是这种类型);
Input
一个数学表达式,只包括数字,数字保证是非负整数,以及五种运算符"+","-","*","/","=";数字和运算符之间有一个或者多个空格,运算符的总数不会超过100,最后以"="号结尾,表示表达式结束。
Output
整数;
Sample Input
1 + 2 + 3 * 6 / 9 =
Sample Output
5

#include <iostream>
#include<algorithm>
#include<string.h>
#include<stack>
using namespace std;
stack<int> S;
char b[100];
int main() {
        while(S.empty()==false)
             {S.pop();
            }
    char a[100];
    gets(a);
    int lengtha= strlen(a);
    int n=0;
    int sum=0;
    for(int i=0;i<lengtha;i++)//去掉空格, 
   {
    if(a[i]!=' ')
    {
        b[n++]=a[i];
    }else
    {
        continue;
    }
     }
    int lengthb=strlen(b);
    int i=0;
     while(i<lengthb)
     {
         if(i==0)
         {
             if(b[i]>='0'&&b[i]<='9')
             {
                  int num=b[i]-'0';
             S.push(num);
             //cout<<S.top()<<endl;
             i++;
             }else if(b[i]=='-')
             {
            int num=-(b[1]-'0');
             S.push(num);
             //cout<<S.top()<<endl;
                  i+=2;
             }
            
         }else if(b[i]=='+'&&b[i+1]>='0'&&b[i+1]<='9')
         {
             int num=b[i+1]-'0';
             S.push(num);
         //    cout<<S.top()<<endl;
             i+=2;
         }else if(b[i]=='-'&&b[i+1]>='0'&&b[i+1]<='9')
         {
             int num=-(b[i+1]-'0');
             S.push(num);
         //    cout<<S.top()<<endl;
             i+=2;
         }else if(b[i]=='*'&&b[i+1]>='0'&&b[i+1]<='9')
         {
             int num=b[i+1]-'0';
             int a=S.top();
             S.pop();
             S.push(a*num);
             i+=2;
         //    cout<<S.top()<<endl;
         } else if(b[i]=='/'&&b[i+1]>='0'&&b[i+1]<='9')
         {
             int num=b[i+1]-'0';
             int a=S.top();
             S.pop();
             S.push(a/num);
             i+=2;
         //    cout<<S.top()<<endl;
         }
         else if(b[i]=='=')
         {
             while(S.empty()==false)
             {
             //    cout<<S.top()<<endl;
                 sum+=S.top();
                 S.pop();        
             }
                 break;
             i++; 
         }
     }
     cout<<sum<<endl;
    return 0;
}

 

posted @ 2016-07-27 22:52  多思考&&多动手  阅读(198)  评论(0编辑  收藏  举报