C++ 邏輯表示式求值
阿新 • • 發佈:2018-12-12
#include<iostream> #include<cstdio> #include<stack> #include<queue> #include<cstring> #include<string> #define N 200 using namespace std; int f(char c); // 求表示式的優先順序 bool f2(char c); // 邏輯表示式數的轉換 string MidToPost(char* c); // 求表示式對應的字尾表示式 char GetValuePost(string c); int main() { char str[N]; string post; char ans; int i = 0; while (gets_s(str, N)) { i++; post = MidToPost(str); ans = GetValuePost(post); printf("Expression %d: %c\n", i, ans); } } int f(char c) { if (c == '(') return 4; if (c == '!') return 3; if (c == '&') return 2; // 相當於* if (c == '|') return 1; // 相當於+,優先順序最低 else return 0; } bool f2(char c) { if (c == 'F') return false; // F相當於0 else return true; // V相當於1 } string MidToPost(char* c) //求表示式對應的字尾表示式 { stack<char> s; //字串中去手動去空格 string q=""; int n = strlen(c); for (int i = 0; i<n; i++) { if (c[i] != ' ') // 除去空格 { // 如果遇到運算數,直接加入到佇列中,用佇列來放字尾表示式 if (c[i] == 'F' || c[i] == 'V') { q += c[i]; } else if (c[i] == '!'&&!s.empty() && s.top() == '!') { s.pop(); // 如果遇到!而且棧頂也是!那麼直接抵消出棧 } else if (!s.size()) { s.push(c[i]); // 如果棧為空,遇到運算子直接入棧 } else if (c[i] == ')') { // 如果是右括號,則彈出對應左括號前的所有的運算子 ,加入到佇列中 while (s.top() != '(') { q += s.top(); s.pop(); } s.pop(); // 彈出左括號 continue; } else if (f(s.top()) == 4 || (f(c[i]) > f(s.top()))) { s.push(c[i]); // 如果棧頂是左括號,或者當前優先順序高,都入棧 } else if (f(s.top()) != 4 && f(c[i]) <= f(s.top())) { q += s.top(); s.pop(); // 如果遇到運算子沒有棧頂運算子級別高,出棧 while (!s.empty() && f(s.top()) != 4 && f(c[i]) <= f(s.top())) { q+=s.top(); // 從棧中彈出比當前優先順序高的運算子 s.pop(); } s.push(c[i]); //將當前運算子加入到佇列 } } } while (!s.empty()) { q += s.top(); // 最後將棧裡面所有元素彈出加入到佇列 s.pop(); } return q; } char GetValuePost(string q) { //字尾表示式求值 bool r = true; char x, y, ans; stack<char> s; int n = q.size(); for (int i = 0; i < n; i++) { if (q[i] == 'V' || q[i] == 'F') { s.push(q[i]); } else { if (q[i] == '&') { x = s.top(); s.pop(); y = s.top(); s.pop(); r == f2(x) && f2(y); if (r == 1) s.push('V'); else s.push('F'); } else if (q[i] == '|') { x = s.top(); s.pop(); y = s.top(); s.pop(); r = f2(x) || f2(y); if (r == 1) s.push('V'); else s.push('F'); } else { x = s.top(); s.pop(); if (f2(x) == 1) s.push('F'); else s.push('V'); } } ans = s.top(); } return ans; }