放置一个“!”在条件语句之前
Placing a "!" before a condition statement
例如:
while (! ( (planet == "Mercury") || (planet == "Pluto") ) )
{
<body>;
}
上面是不是等于说:
while ( (planet != "Mercury") || (planet != "Pluto") )
{
<body>;
}
如果不是,如第一段代码所示,将 NOT 运算放在条件语句之前是什么意思?
等同于
while (planet != "Mercury" && planet != "Pluto")
这是De Morgan's laws in propositional logic
中的一个
使用 C++ 语法,上面的内容是
!(P || Q) == (!P && !Q)
这是 De Morgan's laws 之一的实例。这些定律对于理解如何正确地进行这些类型的转换非常有帮助(根据我的经验,出错是非常常见的事情)。
您应该在 De Morgan's Laws 上阅读。
TLDR 大纲:
!(A || B) = (!A && !B)
!(A && B) = (!A || !B)
这种逻辑非常基础,你会在计算机编程中看到并应用很多。
"while (! ( (planet == "Mercury") || (planet == "Pluto") ) )
" 表示如果这些条件中的任何一个......那些是planet == "Mercury"
和 planet == "Pluto")
......为真则"(! ( (planet == "Mercury") || (planet == "Pluto") ) )
" 将 return 为假。
所以
while (! ( (planet == "Mercury") || (planet == "Pluto") ) )
{
<body>;
}
相当于
while (planet != "Mercury" && planet != "Pluto")
{
<body>;
}
和
while ( (planet != "Mercury") || (planet != "Pluto") )
{
<body>;
}
等同于
while ( !((planet == "Mercury") && (planet == "Pluto") ))
{
<body>;
}
例如:
while (! ( (planet == "Mercury") || (planet == "Pluto") ) )
{
<body>;
}
上面是不是等于说:
while ( (planet != "Mercury") || (planet != "Pluto") )
{
<body>;
}
如果不是,如第一段代码所示,将 NOT 运算放在条件语句之前是什么意思?
等同于
while (planet != "Mercury" && planet != "Pluto")
这是De Morgan's laws in propositional logic
中的一个使用 C++ 语法,上面的内容是
!(P || Q) == (!P && !Q)
这是 De Morgan's laws 之一的实例。这些定律对于理解如何正确地进行这些类型的转换非常有帮助(根据我的经验,出错是非常常见的事情)。
您应该在 De Morgan's Laws 上阅读。
TLDR 大纲:
!(A || B) = (!A && !B)
!(A && B) = (!A || !B)
这种逻辑非常基础,你会在计算机编程中看到并应用很多。
"while (! ( (planet == "Mercury") || (planet == "Pluto") ) )
" 表示如果这些条件中的任何一个......那些是planet == "Mercury"
和 planet == "Pluto")
......为真则"(! ( (planet == "Mercury") || (planet == "Pluto") ) )
" 将 return 为假。
所以
while (! ( (planet == "Mercury") || (planet == "Pluto") ) )
{
<body>;
}
相当于
while (planet != "Mercury" && planet != "Pluto")
{
<body>;
}
和
while ( (planet != "Mercury") || (planet != "Pluto") )
{
<body>;
}
等同于
while ( !((planet == "Mercury") && (planet == "Pluto") ))
{
<body>;
}