扭转逻辑表达

Turning logical expression around

本文关键字:      更新时间:2023-10-16

我有以下代码:

bool s = true;
for (...; ...; ...) {
    // code that defines A, B, C, D 
    // and w, x, y, z
    if (!(A < w) && s == true) {
        s = false;
    }
    if (!(B < x) && s == true) {
        s = false;
    }
    if (!(C < y) && s == true) {
        s = false;
    }
    if (!(D < z) && s == true) {
        s = false;
    }
}

此代码运行良好。但是,出于几个(不重要)原因,我想更改代码,以便我可以启动s = false;并在 if 语句中将其设置为 true。它尝试了以下方法:

bool s = false;
for (...; ...; ...) {
    // code that defines A, B, C, D 
    // and w, x, y, z
    if (A >= w && s == false) {
        s = true;
    }
    if (B >= x && s == false) {
        s = true;
    }
    if (C >= y && s == false) {
        s = true;
    }
    if (D >= z && s == false) {
        s = true;
    }
}

但是,这无法正常工作,因为上面的代码正在工作。我知道逻辑中的某个地方的想法是错误的,但我无法弄清楚在哪里。Anbyone是否看到我可能明显的错误?

编辑:添加了另外三个if状态。错过了他们,因为他们被评论掉了。

摩根定律说,你也应该把&&改成||

!(A < x)

A >= x相同,因此您的函数根本没有反转逻辑。您需要使用A < x .

我可能不会费心检查循环中s的当前状态。要么你翻转它,要么不翻转它。除非有理由继续循环,否则我可能会在翻转sbreak.

我在维基百科页面上找到了德摩根定律的答案。我的问题的正确代码是:

bool s = false;
for (...; ...; ...) {
    // code that defines A, B, C, D 
    // and w, x, y, z
    if (!(A >= w || s == false)) {
        s = true;
    }
    if (!(B >= x || s == false)) {
        s = true;
    }
    if (!(C >= y || s == false)) {
        s = true;
    }
    if (!(D >= z || s == false)) {
        s = true;
    }
}

谢谢@EJP提示!

循环体中设置s的部分在逻辑上等效于以下内容:

if(A >= w || B >= x || C >= y || D >= z)
    s = false;

抽象条件,相当于这样:

s &= some_function(A, B, C, D, w, x, y, z);

您要将其更改为以下内容:

s |= some_other_function(A, B, C, D, w, x, y, z);

在第一种情况下,如果在循环的每次迭代中返回 false,则s在循环后为 true some_function。在第二个 true 中,如果在循环的任何迭代中返回 true,则s在循环之后some_other_function为 true。

some_other_function只有在任何迭代中返回 true 时some_function才能返回 true。但some_other_function只能访问当前迭代中的值。因此,有效的some_other_function不存在。

这是假设s在两种情况下在循环后必须具有相同的值。否则,您可以在与s相关的所有位置轻松交换truefalse

相关文章:
  • 没有找到相关文章