#include<cstdio>
#include<cstdlib>
#include<string>
#include<cstring>
using namespace std;
int number[101],i = 0, p = 1;
char symbol[101],s[256], t[256];
void push() //算符入栈运算
{
symbol[++p] = s[i];
}
void pop() //运算符栈顶元素出栈,并取出操作数栈元素完成相应的运算
{
switch(symbol[p--])
{
case ‘+‘:number[p] += number[p + 1];break;
case ‘-‘:number[p] -= number[p + 1];break;
case ‘*‘:number[p] *= number[p + 1];break;
case ‘/‘:number[p] /= number[p + 1];break;
}
}
bool can() //判断运算符的优先级别,建立标志函数
{
if ((s[i] == ‘+‘ || s[i] == ‘-‘) && symbol[p] != ‘(‘) return 1;
if ((s[i] == ‘*‘ || s[i] == ‘/‘) && (symbol[p] == ‘*‘ || symbol[p] == ‘/‘))return 1;
return 0;
}
int main()
{
printf("String :");
gets(s);
s[strlen(s)] = ‘)‘;
symbol[p] = ‘(‘;
while (i < strlen(s))
{
while (s[i] == ‘(‘) //左括号处理
{
push();i++;
}
int x = 0;
while (s[i] >= ‘0‘ && s[i] <= ‘9‘) //取数入操作数栈
x = x * 10 + s[i++] - ‘0‘;
number[p] = x;
do
{
if (s[i] == ‘)‘) //右括号处理
{
while (symbol[p] != ‘(‘) pop();
number[--p] = number[p + 1];
}
else
{ //根据标志函数值作运算符入栈或出栈运算处理
while (can()) pop();
push();
}
i++;
}while (i < strlen(s) && s[i - 1] == ‘)‘);
}
printf("%d\n",strlen(s));
printf("Result=%d", number[0]);
return 0;
}