计算器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;
}

 

转载于:https://www.cnblogs.com/zhuoyuezai/p/5712939.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值