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 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
| #include<stdio.h> #include<string.h> #include<stdlib.h> #include<iostream> using namespace std; template <class T> class mystack{ T sta[500]; int s_top; public: mystack(){ s_top=0; } void push(T n){ if(s_top>=499) printf("栈满了,进栈失败!\n"); else sta[++s_top]=n; } void pop(){ if(s_top==0) {printf("栈为空,不能出栈。\n");exit(1);} else --s_top; } T top(){ return sta[s_top]; } void clear(){ s_top=0; } bool empty(){ return s_top==0; } int size(){ return s_top; } void printstack(){ int i; for(i=1;i<=s_top;i++) cout<<sta[i]<<" "; printf(" 大小是:%d\n",s_top); } }; mystack<double> ovs; mystack<char> ops; char s[1005]; int comp(char); double calculate(double ,char ,double); int main() { int N; int i,j; double num1,num2; char op; char w[100]; while(printf("请输入算式(输入\"exit\"退出):"),~scanf("%s",s),strcmp(s,"exit")) { ops.push('#'); for(i=0;s[i]!='=';) { printf("当前处理:"); 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'; printf("%s\n",w); ovs.push(atof(w)); } else { if(comp(ops.top())<comp(s[i]) || s[i]=='(') { printf("%c\n",s[i]); ops.push(s[i]); i++; } else if(ops.top()=='(' && s[i]==')') { printf("%c\n",s[i]); ops.pop(); i++; } else { num2=ovs.top(); ovs.pop(); num1=ovs.top(); ovs.pop(); op=ops.top(); ops.pop();
cout<<num1<<" "<<op<<" "<<num2<<endl; ovs.push(calculate(num1,op,num2)); } } printf("运算符当前栈为:"); ops.printstack(); printf("操作数当前栈为:"); ovs.printstack(); printf("\n"); } while(ovs.size()!=1) { printf("当前处理:"); num2=ovs.top(); ovs.pop(); num1=ovs.top(); ovs.pop(); op=ops.top(); ops.pop(); printf("%lf%c%lf\n",num1,op,num2); ovs.push(calculate(num1,op,num2)); } printf("\n\n运算结果:%s%.2lf\n",s,ovs.top()); ovs.clear(); ops.clear(); } return 0; } int comp(char op) { int t; switch(op) { case '*': case '/':t=3;break; case '+': case '-':t=2;break; case '(': case ')':t=1;break; case '#':t=0;break; default :printf("%c_error!\n",op);exit(1); } return t; } 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("%c_error!\n",op);exit(1); } return ans; }
|