[英]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.