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
| #include<stdio.h> #include<stdlib.h> #include<stack> using namespace std; stack<double> ovs; stack<char> ops; char s[1005]; bool comp(char ,char); double calculate(double ,char ,double); int main() { int N; int i,j; double num1,num2,ans; char op; scanf("%d",&N); char w[100]; while(N--) { ops.push('#'); scanf("%s",s); for(i=0;s[i]!='=';) { if(s[i]>='0' && s[i]<='9') { j=0; w[j++]=s[i++]; while((s[i]>='0' && s[i]<='9') || s[i]=='.') { w[j++]=s[i++]; } w[j]='\0'; ovs.push(atof(w)); } else { if(comp(ops.top(),s[i]) || s[i]=='(') { ops.push(s[i]); i++; } else if(ops.top()=='(' && s[i]==')') { ops.pop(); i++; } else { num2=ovs.top(); ovs.pop(); num1=ovs.top(); ovs.pop(); op=ops.top(); ops.pop(); ovs.push(calculate(num1,op,num2)); } } } while(ovs.size()!=1) { num2=ovs.top(); ovs.pop(); num1=ovs.top(); ovs.pop(); op=ops.top(); ops.pop(); ovs.push(calculate(num1,op,num2)); } printf("%.2lf\n",ovs.top()); while(!ovs.empty()) ovs.pop(); while(!ops.empty()) ops.pop(); } return 0; } bool comp(char op_top ,char op) { int top,_op; switch(op_top) { case '*': case '/':top=3;break; case '+': case '-':top=2;break; case '(': case ')':top=1;break; case '#':top=0;break; default :printf("1_error!\n");exit(1); } switch(op) { case '*': case '/':_op=3;break; case '+': case '-':_op=2;break; case '(': case ')':_op=1;break; case '#':_op=0;break; default :printf("2_error!\n");exit(1); } return top<_op; } double calculate(double num1,char op,double num2) { double ans; switch(op) { case '*':ans=num1*num2;break; case '/':ans=num1/num2;break; case '+':ans=num1+num2;break; case '-':ans=num1-num2;break; default :printf("3_error!\n");exit(1); } return ans; }
|