表达式求值
1 #include<stdio.h> 2 #include<string.h> 3 #include<stdlib.h> 4 char str[1005]; 5 int start; 6 char s[50],ss[50];int i,j; 7 double Term();double Expression();double Factor(); 8 double Term() 9 { 10 double f=Factor(),t; 11 --start; 12 if(str[start]=='*') 13 { 14 t=Term(); 15 return t*f; 16 } 17 else if(str[start]=='/') 18 { 19 t=Term(); 20 return t/f; 21 } 22 else {++start;return f;} 23 } 24 double Expression() 25 { 26 double t=Term(),e; 27 --start; 28 if(str[start]=='+') 29 { 30 e=Expression(); 31 return e+t; 32 } 33 else if(str[start]=='-') 34 { 35 e=Expression(); 36 return e-t; 37 } 38 else {++start;return t;} 39 } 40 double Factor() 41 { 42 --start; 43 double ret; 44 if(str[start]==')') 45 { 46 ret=Expression(); 47 --start; 48 return ret; 49 } 50 else 51 { 52 i=0; 53 memset(ss,0,sizeof(ss)); 54 while((str[start]>='0'&&str[start]<='9')||str[start]=='.') 55 s[i++]=str[start--]; 56 ++start; 57 for(j=0;j<i;j++) 58 { 59 ss[j]=s[i-1-j]; 60 } 61 return atof(ss); 62 } 63 } 64 int main() 65 { 66 //freopen("1.txt","r",stdin); 67 int n; 68 scanf("%d",&n); 69 while(n--) 70 { 71 scanf("%s",str); 72 start=strlen(str)-1; 73 printf("%.2lf\n",Expression()); 74 } 75 }