南陽 oj 表達式求值 題目35 數據結構 NYO題目鏈接
阿新 • • 發佈:2017-05-12
pro lin sum tof line 就會 南陽 scan art
??
建議不會的看別人的代碼自己在之上模擬一遍,僅僅要耐心模擬就會做出來
題目鏈接:http://acm.nyist.net/JudgeOnline/problem.php?
pid=35
#include<stdio.h> #include<string.h> #include<stdlib.h> #define N 1000 using namespace std; char s[N];//存儲字符串 char str1[N];//存儲‘o‘-到‘9‘的字符 char str2[N];//存儲運算符 int top1,top2;//利用數組模擬棧 int compare(char x)//優先級比較 { switch(x) { case ‘+‘ : case ‘-‘ :return 1; case ‘*‘ : case ‘/‘ :return 2; case ‘(‘ :return 0; default: return -1; } } void zhuan()//轉換 { int k; top1=-1,top2=-1;//初始化頭 scanf("%s",s); k=strlen(s); for(int i=0;i<k;i++) { if(s[i]>=‘0‘&&s[i]<=‘9‘||s[i]==‘.‘)//假設是數字進去str1數組中 { top1++; str1[top1]=s[i]; } else if(s[i]==‘(‘)//假設是‘(‘進入str2中 { top2++; str2[top2]=s[i]; } else if(s[i]==‘)‘)//假設是‘)‘說明str2中有運算符 { while(str2[top2]!=‘(‘) { top1++; str1[top1]=‘ ‘; top1++; str1[top1]=str2[top2]; top2--; } top2--;//把‘(‘出去 } else if(s[i]==‘+‘||s[i]==‘-‘||s[i]==‘*‘||s[i]==‘/‘)//假設是運算符比較優先級 { top1++; str1[top1]=‘ ‘; while(compare(s[i])<=compare(str2[top2]))//假設s[i]優先級低於之前也就是str2中的運算符 把str2中的運算符給str1 { top1++; str1[top1]=str2[top2]; top1++; str1[top1]=‘ ‘; top2--; } top2++; str2[top2]=s[i];//假設str2高進入str2 } } while(top2!=-1)//將剩余的進入str1中 { top1++; str1[top1]=‘ ‘; top1++; str1[top1]=str2[top2]; top2--; } top1++; str1[top1]=‘ ‘; top1++; str1[top1]=‘=‘; top1++; str1[top1]=‘\0‘; } void sum()//計算 { double a1,a2,d[N]; char ch; char s1[100],st[N]; int k,t=-1; for(int i=0;i<top1;i++) { k=0; ch=str1[i]; while(str1[i]!=‘ ‘) { if(str1[i]==‘=‘) break; s1[k++]=str1[i]; i++; } if(ch>=‘0‘&&ch<=‘9‘) { s1[k]=‘\0‘; t++; d[t]=atof(s1); } else { switch(ch) { case ‘+‘ : a2=d[t]; t--; a1=d[t]; t--; t++; d[t]=a1+a2; break; case ‘-‘ : a2=d[t]; t--; a1=d[t]; t--; t++; d[t]=a1-a2; break; case ‘*‘ : a2=d[t]; t--; a1=d[t]; t--; t++; d[t]=a1*a2; break; case ‘/‘ : a2=d[t]; t--; a1=d[t]; t--; t++; d[t]=a1/a2; break; default : break; } } } printf("%.2lf\n",d[t]); } main() { int n; scanf("%d",&n); while(n--) { zhuan(); sum(); } }
南陽 oj 表達式求值 題目35 數據結構 NYO題目鏈接