【问题标题】:Do-while Loop Conditional Statement Negation EquivalenceDo-while 循环条件语句否定等价
【发布时间】:2019-10-03 15:56:02
【问题描述】:

社区和编程新手。我很好奇为什么这两个逻辑语句在我的程序中是等价的。目前我似乎无法理解这个特定的逻辑,我想了解它为什么会这样工作。

最初,我写了以下内容:

    char c;
    do {
        cin >> c;
        cout << "You entered: " << c << "\n";
    } while (c != 'Y' || c != 'y' || c != 'N' || c || 'n');
    return 0;
}

但是,除非我使用 &&,否则这似乎不起作用。 后来我发现 using or 确实有效,但我的否定肯定是在外面。这是让我感到困惑的两个条件。为什么它们在逻辑上是等价的?

while (!(c == 'Y' || c == 'y' || c == 'N' || c || 'n')); // Will run until c is the following
while (c !='Y' && c != 'y' && c != 'N' && c != 'n'); // Will also run but without being negated.

【问题讨论】:

  • 德摩根定理在这里可能是一个有用的搜索词

标签: c++ logic conditional-statements negation


【解决方案1】:

do-while 循环中的这些逻辑表达式

while (!(c == 'Y' || c == 'y' || c == 'N' || c || 'n')); // Will run until c is the following
while (c == 'Y' && c == 'y' && c == 'N' && c == 'n'); // Will also run but without being negated.

不等价。

表达式

while (!(c == 'Y' || c == 'y' || c == 'N' || c || 'n'));

等价于

while ( c != 'Y' && c != 'y' && c != 'N' && !c && !'n' );

如果你有类似例子的表达式

a == b || c == d

然后它的否定

!( a == b || c == d )

等价于

!( a == b ) && !( c == d )

最后到

a != b && c != d

注意这个do-while循环

char c;
do {
    cin >> c;
    cout << "You entered: " << c << "\n";
} while (c != 'Y' || c != 'y' || c != 'N' || c || 'n');

没有意义。例如,如果用户输入了'N',但循环继续其迭代,因为第一个子表达式c != 'Y' 评估为真。

【讨论】:

  • 哇,速度快得令人难以置信。当我意识到我不小心为 && 条件语句写了“==”并且不得不更正它时,我正在重新编辑发布的问题。我确实知道它们被认为是等效的,但是为什么呢?
猜你喜欢
  • 2020-05-07
  • 1970-01-01
  • 2017-03-08
  • 1970-01-01
  • 1970-01-01
  • 2021-03-08
  • 1970-01-01
  • 1970-01-01
  • 2011-10-23
相关资源
最近更新 更多