/*
表达式求值,需要设置两个栈,操作符栈、数字栈。
add(x,y) sub(x,y) min(x,y) max(x,y)
*/
#include<stdio.h>
#include<ctype.h>
#define MAX 300
int main()
{
freopen("express.in", "r", stdin);
freopen("estdout.pc2", "w", stdout);
int fuhao_stack[MAX], data_stack[MAX], top_f=0, top_d=0;
int indigit=0, sum=0, i, oper, x, y, r, N;
char s[MAX];
scanf("%d", &N);
while(N--)
{
scanf("%s", s);
i=0;
while(s[i]!='\0') //分析字符串,剥离运算符、数字(需要将连续的数字字符合成一个整型数据),
{ //并分别将运算符和整合出来的整数压栈
// printf("=====处理 %c :\n", s[i]); //本句可测试用
if( !isdigit(s[i]) ) //不是数字字符
{
if(indigit) //如果前一个字符是数字,当前字符不是数字,则连续数字字符结束。
{
data_stack[top_d++]=sum;
// printf("sum=%d\n", sum); //本句可测试用
indigit=0; //现在进入非数字字符状态
}
switch(s[i])
{
//printf("\n in s ch=%c\n", s[i]);
case ',': i++; break;
case 'a': fuhao_stack[top_f]=1; top_f++; i=i+4; break;
case 's': fuhao_stack[top_f]=2; top_f++; i=i+4; break;
case 'm':
if(s[i+1]=='i') { fuhao_stack[top_f]=3; top_f++; i=i+4; break; }
else { fuhao_stack[top_f]=4; top_f++; i=i+4; break; }
case ')': //遇到右括号,则可以做运算了(使用最近遇到的运算符)
y=data_stack[--top_d]; //到数字栈里取两个数据。
x=data_stack[--top_d];
oper=fuhao_stack[--top_f]; //到符号栈里取运算符
switch(oper){ //根据运算符做运算
case 1: r=x+y; break;
case 2: r=x-y; break; //做减法时,注意是谁减谁
case 3: r=x<y?x:y; break;
case 4: r=x>y?x:y; break;
}
data_stack[top_d++]=r;
i++; //case ')'
}
} ////不是数字字符
else //是数字字符,转化为整数,累加
{
if(!indigit) ///若是第1个数字字符
{ sum=0; indigit=1; } //累加器清0,准备累加, 设置进入数字状态标志
sum=sum*10+s[i]-'0'; //将数字字符转化成整数,并累加。注意原来的数前移1位(扩大10倍 )
i++;
//printf("\n===sum=%d \n", sum); //本句可测试用
}
}
printf("%d\n", data_stack[top_d-1]);
sum=0;
}
return 0;
}
表达式求值
最新推荐文章于 2024-07-30 18:10:04 发布