这个题我前几天只是做了表达式变换部分,今天把求值部分加进去了。1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
| #include<stdio.h> #include<string.h> #include<stdlib.h> #include<stack> using namespace std; typedef struct Tree { char c; char ss[25]; double n; Tree *liftchild,*rightchild; }tree; stack <tree*> ops; stack <tree*> ovs; tree *Root; char s[1005]; int p(char ch) { switch(ch) { case '*': case '/':return 2; case '+': case '-':return 1; case '(': case ')':return 0; case ';':return -1; default :printf("%c_error!\n",ch);exit(1); } } tree *_build(char *s) { tree *root=new tree; strcpy(root->ss,s); root->liftchild=NULL; root->rightchild=NULL; return root; } tree *build(char ch) { tree *root=new tree; root->c=ch; root->liftchild=NULL; root->rightchild=NULL; return root; } double calcu(double n1,char op,double n2) { switch(op) { case '*':return n1*n2; case '/':return n1/n2; case '+':return n1+n2; case '-':return n1-n2; default :printf("%c_error!",op);return 0; } } void visit(tree * r) { if(r!=NULL) { visit(r->liftchild); visit(r->rightchild); if(r->liftchild==NULL && r->rightchild==NULL) { printf("%s",r->ss); r->n=atof(r->ss);} else { printf("%c",r->c); r->n=calcu(r->liftchild->n,r->c,r->rightchild->n);} } } int main() { int i,j; int N; scanf("%d",&N); char w[100]; while(N--) { scanf("%s",s); for(i=0;s[i]!='=';) { if(s[i]>='0' && s[i]<='9') { j=0; while((s[i]>='0' && s[i]<='9') || s[i]=='.') { w[j++]=s[i++]; } w[j]='\0'; ovs.push(_build(w)); } else { if(ops.empty() || s[i]=='(' || p(ops.top()->c)<p(s[i]) ) ops.push(build(s[i])),i++; else if(ops.top()->c=='(' && s[i]==')') ops.pop(),i++; else { ops.top()->rightchild=ovs.top();ovs.pop(); ops.top()->liftchild=ovs.top();ovs.pop(); Root=ops.top();ops.pop(); ovs.push(Root); } } } while(ovs.size()!=1) { ops.top()->rightchild=ovs.top();ovs.pop(); ops.top()->liftchild=ovs.top();ovs.pop(); Root=ops.top();ops.pop(); ovs.push(Root); } Root=ovs.top();ovs.pop(); while(!ops.empty()) ops.pop(); visit(Root); printf("=\n%.2lf\n\n",Root->n); } return 0; }
|
我觉得不是很难,只要表达式求值你会了,这题也是小意思。