簡單的表示式求值
阿新 • • 發佈:2019-01-31
#include <bits/stdc++.h> using namespace std; #define M 100 char ops[7] = {'+', '-', '*', '/', '(', ')', '='}; char cmp[7][7]= {{'>', '>', '<', '<', '<', '>', '>'}, {'>', '>', '<', '<', '<', '>', '>'}, {'>', '>', '>', '>', '<', '>', '>'}, {'>', '>', '>', '>', '<', '>', '>'}, {'<', '<', '<', '<', '<', '=', ' '}, {'>', '>', '>', '>', ' ', '>', '>'}, {'<', '<', '<', '<', '<', ' ', '='} }; bool check(char ch) { for (int i = 0; i < 7; i++) if (ch == ops[i]) return true; return false; } char C(char ch1, char ch2) { int i, m, n; for (i = 0; i < 7; i++) { if (ch1 == ops[i]) m = i; if (ch2 == ops[i]) n = i; } return cmp[m][n]; } void cal(int x, char op, int y, int &z) { switch (op) { case '+': z = x + y; break ; case '-': z = x - y; break ; case '*': z = x * y; break ; case '/': z = x / y; break ; } } void work(char *str, int &result) { int a, b, v; char ch, op; int temp, i = 0; stack <char> oper; stack <int> num; oper.push('='); ch = str[i++]; while (ch != '=' || oper.top() != '=') { if (check(ch)) { switch (C(oper.top(), ch)) { case '<': oper.push(ch); ch = str[i++]; break; case '=': oper.pop(); ch = str[i++]; break; case '>': op = oper.top(); oper.pop(); b = num.top(); num.pop(); a = num.top(); num.pop(); cal(a, op, b, v); num.push(v); break; } } else { temp = ch - '0'; num.push(temp); ch=str[i++]; } } result = num.top(); printf("%d\n",result); } int main() { int i = 0; int result; char *str; str = new char[M]; cin >> str[i]; while (str[i] != '=') { cin >> str[++i]; } work(str, result); return 0; }