C Language: Expression evaluation implementation (contains subtraction brackets)

Source: Internet
Author: User
Tags arithmetic

This problem is not difficult, but when you seriously to compile code, or to consider a lot of details, so you can not only stay on the level of understanding, do not practice you never know you have no, refueling!

The previous expression evaluation does not include the parentheses operation, now the improved code and source code to stick to the above, easy to review later.

I. Do not include bracket arithmetic

#include <iostream> #include <stdio.h> #include <stdlib.h> #include <string> #include <  Math.h> #define Stack_init_size using namespace std;      typedef struct {char date[stack_init_size];  int top;     }optrstack;      operator struct typedef struct {double date[stack_init_size];  int top;     }opndstack;    operand structure//operator-related operations Optrstack *init_optrstack (); stack empty int empty_optrstack (Optrstack *s);//empty stack int push_optrstack (optrstack *s, char x);//Enter Stack (note: Determine if stack is full) char Pop_optrst ACK (optrstack *s, char x);//Stack (note: Determine if the stack is empty) char Gettop_optrstack (optrstack *s, char x);//Take the top element of the stack, first empty//operand related operation Opndstac K *init_opndstack ();//stack empty int empty_opndstack (Opndstack *t);//empty stack int push_opndstack (Opndstack *t, double y);//Enter Stack (Note: Judge Whether the stack is full) double Pop_opndstack (Opndstack *t, double y);//Stack (note: Determine if the stack is empty) double Gettop_opndstack (Opndstack *t, double y);//Fetch                  Stack top element//Expression evaluation function void Error (char *s);        Error handling function int judge_optr (char ch);      Used to determine if the character ch is an operator int Operate (int a, int b, char top);        Used to calculate the current value and return the value to void Jsbds_operate (char str[]);      Read into the value of a simple arithmetic expression//Operator function Implementation part Optrstack *init_optrstack () {Optrstack *s;      s = (Optrstack *) malloc (sizeof (optrstack));      S->top =-1;  return s;      } int Empty_optrstack (Optrstack *s)//empty stack {if (s->top! =-1) return 1;  else return 0;          } int Push_optrstack (Optrstack *s, char x)//into the stack (note: Determine if the stack is full) {if (S->top = = (stack_init_size-1)) {      return 0;      } else S->date[++s->top] = x;    return 1; } char Pop_optrstack (optrstack *s, char x)//out stack (note: Determine if the stack is empty) {if (!      Empty_optrstack (s)) {return 0;      } else x = s->date[s->top];      s->top--;  return x; } char Gettop_optrstack (optrstack *s, char x)//Take the top element of the stack, first empty {if (!      Empty_optrstack (s)) {return 0;      } else x = s->date[s->top]; ReturnX      }//Operand function Implementation part Opndstack *init_opndstack ()//Stack empty {opndstack *t;      t = (opndstack*) malloc (sizeof (opndstack));      T->top =-1;  return t;      } int Empty_opndstack (Opndstack *t)//empty stack {if (t->top! =-1) return 1;  else return 0;          } int Push_opndstack (Opndstack *t, double y)//into the stack (note: Determine if the stack is full) {if (T->top = = (stack_init_size-1)) {      return 0;      } else t->date[++t->top] = y;  return 1; } double Pop_opndstack (Opndstack *t, double y)//Stack (note: Determine if the stack is empty) {if (!      Empty_opndstack (t)) {return 0;      } Else y = t->date[t->top];      t->top--;  return y; } double Gettop_opndstack (Opndstack *t, double y)//Take the top element of the stack {if (!      Empty_opndstack (t)) {return 0;      } y = t->date[t->top];  return y;      }//Expression evaluation function implements void error (char *s)//error handling function {std::cout << s << endl;  Exit (1); } int Judge_optr (char top)//used to determine if the character ch is an operator {int x;      cout << top << "test" << Endl;      Switch (top) {case ' + ': Case '-': x = 1; Case ' * ': Case '/': x = 2;      Break  } return x;      A double Operate (double b, double A, char top)//is used to calculate the current value and returns the value {double c = 0;          Switch (top) {case ' + ': c = B + A;      Break          Case '-': c = b-a;      Break          Case ' * ': c = b * A;      Break              Case '/': if (a = = 0) {printf ("Denominator is zero!\n");          return 0;          } else C = b/a;      Break          Default:printf ("character entered is illegal!\n");      Break  } return C;     } void Jsbds_operate (char str[])//reads in a simple arithmetic expression and returns the result of the calculation to the main function {Optrstack *optr = Init_optrstack ();     Initialization Operation Fu Yi opndstack *OPND = Init_opndstack ();                               Initializes the operand stack int i, J; I, j is the loop variable, and a, B receives the element of the stack from the operand stack double F;      Receives the value of converting the number of characters to a floating-point count double A = 0;      Double b = 0;      Double c = 0;                           Char d[100];                          Stores the consecutive ' number ' char top = 0 in the string;          Receives the element for the stack from the Operation Ching for (i = 0; str[i]; i++)//Put the elements in the string sequentially into the stack {switch (Str[i]) { Case ' + ':-* * First judge the current operator and operation Fu Top element priority, if above the top of the stack, then the stack, less than the top of the stack element, then from the operand stack sequentially two number, And the operation Ching stack top elements out of the stack, and then from the operand stack out of the two number, according to the operator stack out of operators operation, and the results are pressed into the stack of operations, and then the current operator into the operation Ching. */if (!              Empty_optrstack (OPTR))//When the operation Fu Yi is empty, the stack is saved {push_optrstack (optr, str[i]); } else {a = Pop_opndstack (OPND, a);//Receive a stack of elements from the operand stack B = Pop _opndstack (OPND, b); Receives the element top = Pop_optrstack (Optr, top) out of the stack from the operand stack,//receives the element c = Operate (b, A, top) from the Operation Ching the stack );                 Push_opndstack (OPND, C);              Press the calculated value into the operand stack push_optrstack (optr, str[i]);          } break; Case ' * ': Case '/': if ((! Empty_optrstack (optr)) | |              (Judge_optr (Str[i]) > Judge_optr (Gettop_optrstack (optr, top)))              {//When the action Fu Yi is empty or the precedence of the operator is greater than the top element of the stack is the Push_optrstack (Optr, Str[i]) in the stack; } else {a = Pop_opndstack (OPND, a);//receives the element B = Pop_ from the stack of the operand  Opndstack (OPND, b);//receives the element top = Pop_optrstack (Optr, top) from the stack of operands,//receives the element C from the operation Ching the stack                  Operate (b, A, top);                  Push_opndstack (OPND, C);              Press the calculated value into the operand stack push_optrstack (optr, str[i]);          } case ' n ': break;              default:j = 0;                  do {d[j++] = Str[i];              i++; } while (Str[i] >= ' 0 ' && str[i] <= ' 9 ');                  Can be deposited with one or more numeric characters d[j] = ' + ';              The number of consecutive numeric characters entered into a string i--;                f = atof (d);    Call the library function atoi () to convert the number of characters to floating point Push_opndstack (OPND, F);          Presses the converted number into the operand stack;           }} while (Empty_optrstack (OPTR))//When the operation Fu Yi is not empty, execute {a = Pop_opndstack (OPND, a);//receive the element that is out of the stack from the operand stack b = Pop_opndstack (OPND, b);//receives the element top = Pop_optrstack (Optr, top) from the stack of the operand,//receives the element C from the operation Ching the stack          = Operate (b, A, top);          Push_opndstack (OPND, C);      Presses the computed value into the operand stack} cout << "The expression evaluates to:"; Std::cout << Gettop_opndstack (OPND, c) << endl;//prints the elements in the operand stack (that is, the final result of an expression)} int main () {char str[      100];      Std::cout << "Please enter arithmetic expression (function: +,-,*,/)" << Endl;      CIN >> str;      Jsbds_operate (str);  return 0;   }

Two. Include parentheses operation (paste modification section)

int judge_optr (char top)//is used to determine if the character ch is operator {int x;//cout << top << "test" << endl;switch (top) {case ' (': x = 0; Break;case ' + ': Case '-': x = 1; Break;case ' * ': Case '/': x = 2; Break;case ') ': x = 3; break;} return x;} Double Operate (double b, double A, char top)//is used to calculate the current value and returns the value {double c = 0;switch (top) {case ' + ': c = B + a;break;case '- ': c = b-a;break;case ' * ': c = b * a;break;case '/': if (a = = 0) {printf ("Denominator is zero!\n"); return 0;} Elsec = b/a;break;default:printf ("The character entered is illegal!\n"); return c;}     void Jsbds_operate (char str[])//reads in a simple arithmetic expression and returns the result of the calculation to the main function {Optrstack *optr = Init_optrstack ();     Initialization Operation Fu Yi opndstack *OPND = Init_opndstack ();                               Initializes the operand stack int i, J;                               I,j is the loop variable, and a, B receives the element from the stack of the operand double F;                           Receives the value of converting the number of characters to a floating-point count double A = 0;double b = 0;double c = 0;char d[100];                          Stores the consecutive ' number ' char top = 0 in the string; Receives the element for the stack from the Operation Ching for (i = 0; str[i]; i++)//StringThe elements are sequentially entered into the stack {switch (Str[i]) {case ' (': Case ' + ': '-'): * * First to determine the priority of the top element of the current operator and Operation Fu, if it is higher than the top element of the stack, or less than the top element of the stack, then two digits from the operand stack, And the operation Ching stack top elements out of the stack, and then from the operand stack out of the two number, according to the operator stack out of operators operation, and the results are pressed into the stack of operations, and then the current operator into the operation Ching. */if ((! Empty_optrstack (optr)) | | (Judge_optr (Str[i]) > Judge_optr (Gettop_optrstack (optr, top)) | | (str[i]== ' ('))///When Operation Fu Yi is empty, save {push_optrstack (Optr, Str[i]);} Else{a = Pop_opndstack (OPND, a);//Receive elements from the stack in the operand B = Pop_opndstack (OPND, b);//receive the element top = Pop_optrstack (Optr, T in the stack from the operand stack) OP);//receive the elements from the operation Ching stack C = Operate (b, A, top); Push_opndstack (OPND, c);//press the calculated value into the operand stack push_optrstack (optr, Str[i]);} Break;case ' * ': Case '/': if ((! Empty_optrstack (optr)) | | (Judge_optr (Str[i]) > Judge_optr (Gettop_optrstack (optr, top)) | | (Str[i] = = ' (')) {//When the operation Fu Yi is empty or the precedence of the operator is greater than the top element of the stack is Push_optrstack (optr, Str[i]);} Else{a = Pop_opndstack (OPND, a);//receives the element B = Pop_opndstack (OPND, B) from the stack of operands,//receives the element top of the stack from the operand stack (pop_optrstack, top )///receive the elements from the operation Ching stack C = Operate (b, A, top); Push_opndstack (OPND, c);//press the calculated value into the operand stack for PusH_optrstack (Optr, Str[i]);} Break;case ') ':P ush_optrstack (optr, str[i]); Break;case ' break;default:j ': 0;do{d[j++ =] = str[i];i++;} while (Str[i] &  gt;= ' 0 ' && str[i] <= ' 9 ');                  Can be deposited with one or more numeric characters d[j] = ' + ';                The number of consecutive numeric characters entered is spelled as a string i--;f = Atof (d);    Call the library function atoi () to convert the number of characters to floating point Push_opndstack (OPND, F); Presses the converted number into the operand stack break;}} while (Empty_optrstack (OPTR))//When the operation Fu Yi is not empty, execute {if ((Gettop_optrstack (optr, top) = = ') ') | | (Gettop_optrstack (optr, top) = = ' (')) {Top=pop_optrstack (optr, top);} Else{a = Pop_opndstack (OPND, a);//Receive elements from the stack in the operand B = Pop_opndstack (OPND, b);//receive the element top = Pop_optrstack (Optr, top) from the stack of operands ;//Receive the element c = Operate (b, A, top) from the Operation Ching Stack; Push_opndstack (OPND, c);//press the calculated value into the operand stack}}cout << "The expression evaluates to:"; Std::cout << Gettop_opndstack (OPND, C) << endl;//Prints the elements in the operand stack (that is, the final result of an expression)}


C Language: Expression evaluation implementation (contains subtraction brackets)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.