1362 表达式求值(我写的代码将扩号,和^运算都考虑进去了)
-
描述:对于一个不存在括号的表达式进行计算(包含加减乘除四种运算符,除法为向下取整)。
-
输入:多组数据,每组数据占据一行。
-
输出:输出计算结果。
-
输入示例
6/2+3+3*4 734/2-56*2-7*8
-
输出示例
18 199
-
代码块
#include <bits/stdc++.h> using namespace std; void cal(string s){ stack<char> ops; stack<int> nums; int num = 0; for(int i=0; i<s.size(); ++i){ if(s[i] >= '0' && s[i] <= '9'){//扫描到操作数,压入栈中 num = num*10 + s[i] - '0'; }else{ if(s[i] == '('){ ops.push(s[i]); }else if(s[i] == ')'){ nums.push(num); num = 0; while(!ops.empty() && ops.top() != '('){ //每弹出一个操作符都要弹出两个操作数进行相应的计算,计算结果在压会栈中 int a = nums.top(); nums.pop(); int b = nums.top(); nums.pop(); nums.push(jisuan(b, a, ops.top())); ops.pop(); } ops.pop(); }else if(s[i] == '^'){ if(s[i-1] != ')'){ //特别注意当s[i]的前面是'('和')'的时候,由于'('和')'不是操作数,千万不能将num放入栈中的 nums.push(num); num = 0; } //扫描到界限符或操作符,按照中缀转后辍相同的规则压入运算栈(期间会弹出运算符) while(!ops.empty() && ops.top() == '^'){ //每弹出一个操作符都要弹出两个操作数进行相应的计算,计算结果在压会栈中 int a = nums.top(); nums.pop(); int b = nums.top(); nums.pop(); nums.push(jisuan(b, a, ops.top())); ops.pop(); } ops.push(s[i]); }else if(s[i] == '*' || s[i] == '/'){ if(s[i-1] != ')'){//特别注意当s[i]的前面是'('和')'的时候,由于'('和')'不是操作数,千万不能将num放入栈中的 nums.push(num); num = 0; } while(!ops.empty() && ops.top() != '(' && ops.top() != '+' && ops.top() != '-'){ //每弹出一个操作符都要弹出两个操作数进行相应的计算,计算结果在压会栈中 int a = nums.top(); nums.pop(); int b = nums.top(); nums.pop(); nums.push(jisuan(b, a, ops.top())); ops.pop(); } ops.push(s[i]); }else if(s[i] == '+'|| s[i] == '-'){ if(s[i-1] != ')'){//特别注意当s[i]的前面是'('和')'的时候,由于'('和')'不是操作数,千万不能将num放入栈中的 nums.push(num); num = 0; } while(!ops.empty() && ops.top() != '('){ int a = nums.top(); nums.pop(); int b = nums.top(); nums.pop(); nums.push(jisuan(b, a, ops.top())); ops.pop(); } ops.push(s[i]); } } if(i == s.size()-1 && s[i] >= '0' && s[i] <= '9') nums.push(num); } while(!ops.empty()){ int a = nums.top(); nums.pop(); int b = nums.top(); nums.pop(); nums.push(jisuan(b, a, ops.top())); ops.pop(); } cout << nums.top() << endl; } int jisuan(int a, int b, char ch){ switch(ch){ case '+': return a + b; case '-': return a - b; case '*': return a * b; case '/': return a / b; case '^': return pow(a, b); } return 0; }