NYOJ 35 表达式求值
生活随笔
收集整理的這篇文章主要介紹了
NYOJ 35 表达式求值
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
表達式求值
時間限制:3000?ms ?|? 內存限制:65535?KB 難度:4 描述比如輸入:“1+2/4=”,程序就輸出1.50(結果保留兩位小數) 輸入
每組測試數據只有一行,是一個長度不超過1000的字符串,表示這個運算式,每個運算式都是以“=”結束。這個表達式里只包含+-*/與小括號這幾種符號。其中小括號可以嵌套使用。數據保證輸入的操作數中不會出現負數。
數據保證除數不會為0
AC碼:
#include<stdio.h> #include<string.h> char str[3000]; int t; double eval() {double x=0,m;if(str[t]==' ')t--;if(str[t]=='+'){t--;return eval()+eval();}if(str[t]=='-'){t--;return eval()-eval();}if(str[t]=='*'){t--;return eval()*eval();}if(str[t]=='/'){t--;return eval()/eval();}while(str[t]>='0'&&str[t]<='9'){x=x*10+str[t]-'0';t--;}if(str[t]=='.'){t--;m=0.1;while(str[t]>='0'&&str[t]<='9'){x=x+(str[t]-'0')*m;m=m*0.1;t--;}}return x; } int main() {int top,count,T,len,i;char ch[1005],pt[1000];scanf("%d",&T);while(T--){scanf("%s",ch);len=strlen(ch);top=-1;memset(pt,0,sizeof(pt));count=-1;for(i=len-2;i>=0;i--){if(ch[i]>='0'&&ch[i]<='9'){while(ch[i]=='.'||(ch[i]>='0'&&ch[i]<='9')){top++;str[top]=ch[i];i--;}top++;str[top]=' ';}if(i<0)break;if(ch[i]==')'){count++;pt[count]=ch[i];} else if(ch[i]=='('){while(count>=0&&pt[count]!=')'){top++;str[top]=pt[count];count--;top++;str[top]=' ';}count--;}else if(ch[i]=='*'||ch[i]=='/'){count++;pt[count]=ch[i];}else{while((pt[count]=='*'||pt[count]=='/')&&count>=0&&pt[count]!=')'){top++;str[top]=pt[count];top++;str[top]=' ';count--;}count++;pt[count]=ch[i];}}// printf("%d\n",count);while(count>=0){if(pt[count]!=')'){top++;str[top]=pt[count];top++;str[top]=' ';count--;}}str[top]='\0';//printf("%s\n",str);t=strlen(str)-1;printf("%.2f\n",eval());}return 0; }總結
以上是生活随笔為你收集整理的NYOJ 35 表达式求值的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 木兰编程语言当事人被停职:自主创新何时当
- 下一篇: redis分布式锁,面试官请随便问,我都