题目1101:计算表达式
时间限制:1 秒
内存限制:32 兆
特殊判题:否
提交:4036
解决:1227
-
题目描述:
-
对于一个不存在括号的表达式进行计算
-
输入:
-
存在多种数据,每组数据一行,表达式不存在空格
-
输出:
-
输出结果
-
样例输入:
-
6/2+3+3*4
-
样例输出:
-
18
-
来源:
/**
一半情况下,需要使用连个栈,一个用来存放数字,一个用来存放运算符。
还要设置运算符的优先级(有括号是更麻烦)。但这道题不用那么麻烦,因为题目中没有括号和空格
因此可以简化。
在读取时,遇到"*"和"/"就从栈中弹出一个数字进行运算,当遇到"+"是,就直接进栈,
当遇到"-"时,就将数字的相反数(如读到"-"时,将-b入栈)。最后,将栈中所有的数字
相加就行了。
**/
#include<stdio.h>
#include<string.h>
#include<stack>
#include<algorithm>
using namespace std;
stack<int>s;
char str[100];
int pos;
int getNumber(char str[])
{
int num=0;
while(str[pos]>='0'&&str[pos]<='9')
{
num=num*10+(str[pos]-'0');
pos++;
}
return num;
}
int main()
{
while(scanf("%s",str)!=EOF)
{
while(!s.empty())
{
s.pop();
}
pos=0;
int a,b;
a=getNumber(str);
s.push(a);
while(str[pos]!='\0')
{
if(str[pos]=='*')
{
pos++;
b=getNumber(str);
a=s.top();
s.pop();
s.push(a*b);
}
else if(str[pos]=='/')
{
pos++;
b=getNumber(str);
a=s.top();
s.pop();
s.push(a/b);
}
else if(str[pos]=='+')
{
pos++;
b=getNumber(str);
s.push(b);
}
else if(str[pos]=='-')
{
pos++;
b=getNumber(str);
s.push(-b);
}
}
int ans=0;
while(!s.empty())
{
ans=ans+s.top();
s.pop();
}
printf("%d\n",ans);
}
return 0;
}