/*
表達式求值,需要設置兩個棧,操作符棧、數字棧。
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;
}
表達式求值
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.