括号匹配
//裁剪字符串,掐头去尾只保留被括号包围的部分 void trim(const char exp[], int& lo, int& hi) { while ((lo <= hi) && (exp[lo] != '(') && (exp[lo] != ')')) lo++; while ((lo <= hi) && (exp[hi] != '(') && (exp[hi] != ')')) hi--; } //分割字符串,分割成左右,即"("与")"括号相同的多个部分 int divide(const char exp[], int lo, int hi) { int mi = lo; int crc = 1; while ((0 < crc) && (++mi < hi)) { if (exp[mi] == ')') crc--; if (exp[mi] == '(') crc++; } return mi; } //综合上述两部分,递归求解 bool paren(const char exp[], int lo, int hi) { trim(exp, lo, hi); if (lo > hi) return true; if (exp[lo] != '(') return false; if (exp[hi] != ')') return false; int mi = divide(exp, lo, hi); if (mi > hi) return false; return paren(exp, lo + 1, mi - 1) && paren(exp, mi + 1, hi); }
对字符串形式的数学表达式求值
下面这段程序用到了指针的引用,与指针的主要区别在于调用函数中形参列表对其声明的方式不同,指针的声明形如:int* a 指针的引用声明形如:int*& a 其详细解读可网上搜索。
#define N_OPTR 9 typedef enum { ADD, SUB, MUL, DIV, POW, FAC, L_P, R_P, EOE } Operator; const char pri[N_OPTR][N_OPTR] = { '>','>','<','<','<','<','<','>','>', '>','>','<','<','<','<','<','>','>', '>','>','>','>','<','<','<','>','>', '>','>','>','>','<','<','<','>','>', '>','>','>','>','>','<','<','>','>', '>','>','>','>','>','>',' ','>','>', '<','<','<','<','<','<','<','=',' ', ' ',' ',' ',' ',' ',' ',' ',' ',' ', '<','<','<','<','<','<','<',' ','=' }; void readNumber(char*& p, stack<float>& stk) { float stkr; stk.push((float)(*p - '0')); while (isdigit(*(++p))) { stkr=stk.top() * 10 + (*p - '0'); stk.pop(); stk.push(stkr); } if ('.' != *p) return; float fraction = 1; while (isdigit(*(++p))) { stkr = stk.top() + (fraction /= 10) * (*p - '0'); stk.pop(); stk.push(stkr); } } Operator optr2rank(char op) { switch (op) { case '+': return ADD; case '-': return SUB; case '*': return MUL; case '/': return DIV; case '^': return POW; case '!': return FAC; case '(': return L_P; case ')': return R_P; case '