NYOJ 35 表达式求值
生活随笔
收集整理的這篇文章主要介紹了
NYOJ 35 表达式求值
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
表達(dá)式求值
時(shí)間限制:3000?ms ?|? 內(nèi)存限制:65535?KB 難度:4 描述比如輸入:“1+2/4=”,程序就輸出1.50(結(jié)果保留兩位小數(shù)) 輸入
每組測(cè)試數(shù)據(jù)只有一行,是一個(gè)長(zhǎng)度不超過(guò)1000的字符串,表示這個(gè)運(yùn)算式,每個(gè)運(yùn)算式都是以“=”結(jié)束。這個(gè)表達(dá)式里只包含+-*/與小括號(hào)這幾種符號(hào)。其中小括號(hào)可以嵌套使用。數(shù)據(jù)保證輸入的操作數(shù)中不會(huì)出現(xiàn)負(fù)數(shù)。
數(shù)據(jù)保證除數(shù)不會(huì)為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; }總結(jié)
以上是生活随笔為你收集整理的NYOJ 35 表达式求值的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 木兰编程语言当事人被停职:自主创新何时当
- 下一篇: redis分布式锁,面试官请随便问,我都