例如:用栈计算5-(7*(5-3)+2)*3的值
提示:需要构建数字栈和符号栈两个栈实现,注意优先级的比较:
#include #include using namespace std; #define MAXSIZE 100 void calculate(const char arr[], int length); bool isCompare(char a, char b); static map kv; void cal(int numStack[], const char opStack[], int &top_num, int &top_op); void initX(); int main(){ initX(); char arr[] = {'5','-','(','7','*','(','5','-','3',')','+','2',')','*','3'}; int length = sizeof (arr); calculate(arr, length); return 0; } void calculate(const char arr[], int length){ int numStack[MAXSIZE]; char opStack[MAXSIZE]; int top_num = -1; int top_op = -1; for(int i=0;i-1){ cal(numStack, opStack, top_num, top_op); } cout << "计算结果:" << numStack[top_num--] << endl; } bool isCompare(char a, char b){ return kv.find(a)->second > kv.find(b)->second; } void initX(){ kv['+'] = 1; kv['-'] = 1; kv['*'] = 2; kv['/'] = 2; } void cal(int numStack[], const char opStack[], int &top_num, int &top_op){ int a,b; char op = opStack[top_op--]; switch(op){ case '+': a = numStack[top_num--]; b = numStack[top_num--]; numStack[++top_num] = b+a; break; case '-': a = numStack[top_num--]; b = numStack[top_num--]; numStack[++top_num] = b-a; break; case '*': a = numStack[top_num--]; b = numStack[top_num--]; numStack[++top_num] = b*a; break; case '/': a = numStack[top_num--]; b = numStack[top_num--]; numStack[++top_num] = b/a; break; default: return; } }
上一篇 C++11=default,=delete
下一篇 C++格式化输出
版权所有 (c)2021-2022 MSHXW.COM
ICP备案号:晋ICP备2021003244-6号