转向逻辑表达式

时间:2013-11-10 08:46:31

标签: c++ if-statement logic

我有以下代码:

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-statemets。错过了他们,因为他们被评论了。

4 个答案:

答案 0 :(得分:2)

De Morgan's laws说,您还应该将&&更改为||

答案 1 :(得分:0)

!(A < x)A >= x相同,因此您的功能根本没有颠倒逻辑。您需要使用A < x

我可能不会在循环中检查s的当前状态。无论是你翻转还是不翻。除非有理由继续循环,否则在翻转break之后我可能会s

答案 2 :(得分:0)

我在Wikipedias page on De Morgan's laws找到了答案。我的问题的正确代码是:

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提示!

答案 3 :(得分:0)

设置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);

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

如果some_other_function在任何迭代中都返回true,则

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

假设s在两种情况下循环后必须具有相同的值。否则,您可以在与true相关的所有地方轻松交换falses

相关问题