# 计算器2

218人阅读 评论(0)

Input

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;
}

0
0

个人资料
• 访问：72960次
• 积分：1367
• 等级：
• 排名：千里之外
• 原创：149篇
• 转载：8篇
• 译文：0篇
• 评论：5条
最新评论