四则运算表达式求值
题意:设计一个计算器,实现+-*/以及()的表达式运算求值。
栈的应用,这学期学数据结构,手写了栈练一下~
1 #include <bits/stdc++.h> 2 using namespace std; 3 const int maxn=10010; //最大表达式长度 4 5 template <typename T> 6 class Stack; 7 8 template <typename T> 9 class Node{ 10 friend Stack<T>; 11 private: 12 T x; 13 Node<T> *nxt; 14 }; 15 16 template <typename T> 17 class Stack{ 18 public: 19 Stack() {head=NULL;} 20 virtual ~Stack(){if(head) delete head;} 21 virtual void init() {head=NULL;} 22 virtual bool _empty() const {return head==NULL;} 23 virtual T top() const; 24 virtual void pop(); 25 virtual void push(const T a); 26 private: 27 Node<T> *head; 28 }; 29 30 template <typename T> 31 T Stack<T>::top() const{ 32 return head->x; 33 } 34 35 template <typename T> 36 void Stack<T>::pop(){ 37 head=head->nxt; 38 } 39 40 template <typename T> 41 void Stack<T>::push(const T a){ 42 Node<T> *tmp=new Node<T>(); 43 tmp->x=a; 44 tmp->nxt=head; 45 head=tmp; 46 } 47 48 char s[maxn]; 49 Stack<char> op; 50 Stack<double> num; 51 void cal(){ 52 double x=num.top();num.pop(); 53 double y=num.top();num.pop(); 54 char c=op.top();op.pop(); 55 switch(c){ 56 case ‘+‘: 57 num.push(x+y); 58 break; 59 case ‘-‘: 60 num.push(y-x); 61 break; 62 case ‘*‘: 63 num.push(x*y); 64 break; 65 case ‘/‘: 66 num.push(y/x); 67 break; 68 } 69 return ; 70 } 71 bool check(char c1,char c2){ 72 int a,b; 73 double x=num.top();num.pop(); 74 if(num._empty()) {num.push(x); return 0;} 75 else num.push(x); 76 77 switch (c1){ 78 case ‘+‘: a=0;break; 79 case ‘-‘: a=0;break; 80 case ‘*‘: a=1;break; 81 case ‘/‘: a=1;break; 82 case ‘(‘: a=-1;break; 83 } 84 switch (c2){ 85 case ‘+‘: b=0;break; 86 case ‘-‘: b=0;break; 87 case ‘*‘: b=1;break; 88 case ‘/‘: b=1;break; 89 } 90 return a>=b; 91 } 92 93 int main(){ 94 while(cin>>s){ 95 op.init(); 96 num.init(); 97 int len=strlen(s); 98 for(int i=0;i<len;i++){ 99 if(isdigit(s[i])) { 100 double x=atof(&s[i]); 101 while(i<len&&(s[i+1]==‘.‘||isdigit(s[i+1]))) i++; 102 num.push(x); 103 } 104 else{ 105 if(s[i]==‘(‘){ 106 op.push(s[i]); 107 }else if(s[i]==‘)‘){ 108 while(!op._empty()&&op.top()!=‘(‘){ 109 cal(); 110 } 111 op.pop(); 112 }else if(s[i]==‘=‘){ 113 while(!op._empty()) 114 cal(); 115 }else if(op._empty()){ 116 op.push(s[i]); 117 }else { 118 while(!op._empty()&&check(op.top(),s[i])){ 119 cal(); 120 } 121 op.push(s[i]); 122 } 123 124 } 125 } 126 while(!op._empty()) cal(); 127 printf("%.2lf\n",num.top()); 128 } 129 return 0; 130 }
时间: 2024-10-25 11:22:04