-
题目描述:
-
对于一个不存在括号的表达式进行计算
-
输入:
-
存在多种数据,每组数据一行,表达式不存在空格
-
输出:
-
输出结果
-
样例输入:
-
6/2+3+3*4
-
样例输出:
-
18
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
用栈模拟计算表达式,一般情况下,根据数据结构上介绍要建立操作数与操作符两个栈,并且设立优先级,根据优先级进行计算。但此题中有说明:没有括号,表达式不含空格,只有加、减、乘、除,因此可以简化,不必设立优先级,在读取时,遇到乘除时,直接从栈中弹出数据计算,因为按顺序计算先碰到乘除符号优先级最高;如果遇到减号,可以将后面的数据看成是负数。因此,简化之后,当遍历结束只需要将栈中的数据相加即为结果。
#include<stdio.h>
#include<stack>
using namespace std;
#define SIZE 100
char buf[SIZE];
int pos;
int getnum(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",buf)!=EOF)
{
stack<int>s;
int a,b;
pos=0;
a=getnum(buf);
s.push(a);
while(buf[pos]!='\0')
{
if(buf[pos]=='*')
{
pos++;
b=getnum(buf);
a=s.top();
s.pop();
s.push(a*b);
}else if(buf[pos]=='/')
{
pos++;
b=getnum(buf);
a=s.top();
s.pop();
s.push(a/b);
}else if(buf[pos]=='-')
{
pos++;
b=getnum(buf);
s.push(-b);
}else
{
pos++;
b=getnum(buf);
s.push(b);
}
}
int result=0;
while(!s.empty())
{
result+=s.top();
s.pop();
}
printf("%d\n",result);
}
return 0;
}