How to evaluate with C++ expression
This article mainly explains "how to evaluate with C++ expression". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought slowly and deeply. Let's study and learn how to evaluate C++ expressions.
Catalogue
one。 Detail handling:
1. Note that negative numbers require string preprocessing.
two。 Consider a divisor of 0
3. The original string plus a delimiter'#'
4. Priority:
two。 Key points of knowledge:
three。 Complete source code:
one。 Details: 1. Note that negative numbers therefore require string preprocessing string format (string str) {int len = str.length (); for (int I = 0; I)
< len; i++) { if (str[i] == '-') { if (i == 0) { str.insert(0, 1, '0'); }//处理-3*2+1情况 else if (str[i - 1]=='(') { str.insert(i, 1, '0'); }//处理(-3*4+1)情况 } } return str;}2.考虑除数为0case '/': if (0 != y) { res = x / y; } else { cout ='0&&str[i]str1 = str + '#';//以定界符开头}Expression :: ~_Expression() {}//将中缀表达转为后缀表达int Expression::Compute(){ int Num[100], Symbol[100];//定义存操作数和运算符的两个栈 int i, k, x, y, res; char op; Symbol[0] = '#'; int top1 = -1, top2 = 0; for (i = 0; str1[i] != '\0';) { if (str1[i] >='0' & str1 [I]