[英]Evaluating boolean expression with recursive
我编写了一个程序来递归评估 boolean 表达式。 但是当我使用输入"(1|1)"
运行时,在 function S 的第二次递归中,特别是在result = result || P()
result = result || P()
而不是 step into P()
,它通过该行并返回结果。 但是,它适用于输入"(~1|1)"
。 我怎样才能解决这个问题?
#include <stdbool.h>
#include <stdlib.h>
char *s;
char *f;
bool P(), A();
// The grammar is:
// S -> P||S | P&&S | P
// P -> A | ~A
// A -> (S) | 0 | 1
bool S() {
bool result = P();
if (*s == '|') {
s++;
result = result || P();
}
else
if (*s == '&') {
s++;
result = result && P();
}
return result;
}
bool P() {
if (*s == '~') {
s++;
return !A();
}
else
{
return A();
}
}
bool A() {
bool result;
if (*s == '(') {
s++;
result = S();
if (*s == ')') s++;
else {
printf("Syntaktisch falsch! Stelle %ld, Art: Anzahl von '(' und ')' sind nicht gleich\n", s-f);
exit(1);
}
}
else
if (*s == '1') {
s++;
result = true;
}
else
if (*s == '0') {
s++;
result = false;
}
else {
printf("Syntaktisch falsch! Stelle: %ld, Art: Boolscher Ausdruck fehlt\n", s-f); // Hier gibt Fehlermeldung aus, wenn Input String ist nur '~'.
exit(1);
}
return result;
}
int main(int argc, char *argv[])
{
bool result;
if (argc != 2) exit(1);
s = argv[1];
f = s;
result = S();
printf("%d\n", result);
return 0;
}
result || P()
result || P()
只要求其中一个值 - result
或P()
- 为 TRUE 以满足表达式。 如果result
为 TRUE 当result || P()
评估result || P()
不需要调用 function - 这称为“短路评估”。 将您的代码更改为:
bool p_val;
p_val = P();
result = result || p_val;
为了确保 function 被实际调用。
result = result || P();
如果result
为true
, P
将永远不会被调用
result = result && P();
如果result
为false
, P
将永远不会被调用
所以首先拨打电话以确保它被调用。
P() || result
P() && result
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.