C++说明逻辑表达式的定义如下:单个true或false都是逻辑表达式;如果S及T是逻辑表达式那么S and T也是逻辑表达式;如果S及T是逻辑表达式那么S or T也是逻辑表达式。对逻辑表达式求值前需要确定and与or运算的优先级:若规定先算and再算or则以下表达式的值为 true or false and false or false ~~~~~~~~~~~~~~~
#include
bool evaluateExpression(string expression, bool conjunctionFirst) {
stack
for (int i = 0; i < expression.length(); i++) {
if (expression[i] == ' ') {
continue;
} else if (expression[i] == 'true') {
operands.push(true);
} else if (expression[i] == 'false') {
operands.push(false);
} else if (expression[i] == 'and' || expression[i] == 'or') {
operators.push(expression[i]);
} else if (expression[i] == '(') {
operators.push(expression[i]);
} else if (expression[i] == ')') {
while (!operators.empty() && operators.top() != '(') {
char op = operators.top();
operators.pop();
bool operand2 = operands.top();
operands.pop();
bool operand1 = operands.top();
operands.pop();
if (op == 'and') {
operands.push(operand1 && operand2);
} else if (op == 'or') {
operands.push(operand1 || operand2);
}
}
if (!operators.empty()) {
operators.pop(); //pop '('
}
}
}
while (!operators.empty()) {
char op = operators.top();
operators.pop();
bool operand2 = operands.top();
operands.pop();
bool operand1 = operands.top();
operands.pop();
if (op == 'and') {
operands.push(operand1 && operand2);
} else if (op == 'or') {
operands.push(operand1 || operand2);
}
}
return operands.top();
}
int main() { string expression; getline(cin, expression);
bool resultConjunctionFirst = evaluateExpression(expression, true);
bool resultDisjunctionFirst = evaluateExpression(expression, false);
cout << (resultConjunctionFirst ? "true" : "false") << endl;
cout << (resultDisjunctionFirst ? "true" : "false") << endl;
return 0;
原文地址: http://www.cveoy.top/t/topic/inLe 著作权归作者所有。请勿转载和采集!