用C++编程实现计算带小括号和加减乘除(整除)的算术表达式
输入一个表达式,输出其值。
代码:
#include <iostream> #include <cstdio> #include <cstring> #include <cmath> using namespace std; struct Expression { Expression *father; int top; long long number[101]; char symbol[101]; Expression *child[101]; }*p; string expression; int lenExpression; long long Work(Expression *workExpression); int main(int argc, char const *argv[]) { cin >> expression; lenExpression = expression.length(); p = new Expression; p->top = 0; p->father = NULL; memset(p->symbol, 0, sizeof(p->symbol)); memset(p->number, 0, sizeof(p->number)); for (int i=0; i<lenExpression; i++) { if (expression[i] == '(') { (p->top)++; p->child[p->top] = new Expression; p->child[p->top]->father = p; p = p->child[p->top]; p->top = 0; memset(p->number, 0, sizeof(p->number)); memset(p->symbol, 0, sizeof(p->symbol)); } else if (expression[i] == ')') { p = p->father; } else if (expression[i]>='0' && expression[i]<='9') { if (p->child[p->top]!=NULL or p->symbol[p->top]!=0 or p->top==0) { (p->top)++; } p->number[p->top] = (p->number[p->top])*10+(expression[i]-'0'); p->child[p->top] = NULL; } else { (p->top)++; p->symbol[p->top] = expression[i]; p->child[p->top] = NULL; } } while (p->father != NULL) { p = p->father; } cout << Work(p) << endl; return 0; } long long Work(Expression *workExpression) { long long ans = 0; for (int i=1; i<=workExpression->top; ) { if (workExpression->child[i] != NULL) { workExpression->number[i] = Work(workExpression->child[i]); workExpression->child[i] = NULL; } if (workExpression->child[i]==NULL and workExpression->symbol[i]==0) { if (i >= 3) { if (workExpression->symbol[i-1] == '*') { workExpression->number[i-2] *= workExpression->number[i]; for (int j=i-1; j<workExpression->top-1; j++) { workExpression->child[j] = workExpression->child[j+2]; workExpression->number[j] = workExpression->number[j+2]; workExpression->symbol[j] = workExpression->symbol[j+2]; } workExpression->top -= 2; } else if (workExpression->symbol[i-1] == '/') { workExpression->number[i-2] /= workExpression->number[i]; for (int j=i-1; j<workExpression->top-1; j++) { workExpression->child[j] = workExpression->child[j+2]; workExpression->number[j] = workExpression->number[j+2]; workExpression->symbol[j] = workExpression->symbol[j+2]; } workExpression->top -= 2; } else { i++; } } else { i++; } } else { i++; } } char sbl = '+'; for (int i=1; i<=workExpression->top; i++) { if (workExpression->symbol[i] == '+') { sbl = '+'; } else if (workExpression->symbol[i] == '-') { sbl = '-'; } else { if (sbl == '+') { ans += workExpression->number[i]; } else { ans -= workExpression->number[i]; } } } return ans; }