Description
The objective of the program you are going to produce is to evaluate boolean expressions as the one shown next:
Expression: ( V | V ) & F & ( F | V )
where V is for True, and F is for False. The expressions may include the following operators: ! for not , & for and, | for or , the use of parenthesis for operations grouping is also allowed.
To perform the evaluation of an expression, it will be considered the priority of the operators, the not having the highest, and the or the lowest. The program must yield V or F , as the result for each expression in the input file.
Input
The expressions are of a variable length, although will never exceed 100 symbols. Symbols may be separated by any number of spaces or no spaces at all, therefore, the total length of an expression, as a number of characters, is unknown.
The number of expressions in the input file is variable and will never be greater than 20. Each expression is presented in a new line, as shown below.
Output
For each test expression, print "Expression " followed by its sequence number, ": ", and the resulting value of the corresponding test expression. Separate the output for consecutive test expressions with a new line.
Use the same format as that shown in the sample output shown below.
Sample Input
( V | V ) & F & ( F| V) !V | V & V & !F & (F | V ) & (!F | F | !V & V) (F&F|V|!V&!F&!(F|F&V))
Sample Output
Expression 1: F Expression 2: V Expression 3: V
题目链接:http://poj.org/problem?id=2106
题意:
求逻辑表达式的值,真或假,可能会含有若干的空格。
思路:
优先级:! > && > || 逻辑表达式也同样符合表达式的定义,表达式是由若干的项“||”操作组成, 项是由若干个因子通过“&&”操作组成, 因子由单个F或V组成,也可由带括号的表达式组成。"!"操作同样作为因子的一部分。最后按照定义递归进行即可。
代码:
#include <iostream> #include <stdio.h> #include <cstring> #include <algorithm> using namespace std; char ep[110]; int k; int factor_value() { int expression_value(void); int ret = 0; int flag = 0; while (ep[k] == ‘!‘) { k++; flag = ~flag; } if (ep[k] == ‘(‘) { k++; ret = expression_value(); k++; } else { if (ep[k] == ‘F‘) { k++; ret = 0; } else if (ep[k] == ‘V‘){ ret = 1; k++; } } if (flag) return !ret; else return ret; } int term_value() { int ret = factor_value(); while (1) { if (ep[k] == ‘&‘) { k++; ret = factor_value()&&ret; //同下解释 } else break; } return ret; } int expression_value() { int ret = term_value(); while (1) { if (ep[k] == ‘|‘) { k++; ret = term_value() || ret; } //term_vaue()一定要写到前面,否则ret为真,term_value就不进行了 else break; } return ret; } int main() { //freopen("1.txt", "r", stdin); char ori[100001]; int t = 0; while (cin.getline(ori, 100000)) { int j = 0; for (int i = 0; ori[i]; i++) { if (ori[i] != ‘ ‘) ep[j++] = ori[i]; } ep[j] = ‘\0‘; //cout << ep << endl; k = 0; printf("Expression %d: ", ++t); if (expression_value()) printf("V\n"); else printf("F\n"); } return 0; }