【问题标题】:false || true giving 0 in MinGW Compiler v 6.3.0-1假 ||在 MinGW Compiler v 6.3.0-1 中真正给出 0
【发布时间】:2018-05-15 02:55:11
【问题描述】:

这是我写的一个 C++ 程序:

#include <iostream>
using namespace std;

int main() {

    cout << "\n" << "false || false" << ": " << false || false;
    cout << "\n" << "false || true" <<  ": " << false || true;
    cout << "\n" << "true || false" << ": " <<  true || false;
    cout << "\n" << "true || true" << ": " <<  true || true;
    cout << "\n" << "false && false" << ": " << false && false;
    cout << "\n" << "false && true" << ": " << false && true;
    cout << "\n" << "true && false" << ": " << true && false;
    cout << "\n" << "true && true" << ": " << true && true;

    return 0;
}

这是输出。

false || false: 0
false || true: 0
true || false: 1
true || true: 1
false && false: 0
false && true: 0
true && false: 1
true && true: 1

有人可以向我解释为什么 false || true0 吗?我正在使用 MinGW C++ 编译器版本 6.3.0-1。

【问题讨论】:

  • 将表达式括在括号中。
  • @0x499602D2:哦,好吧。谢谢。

标签: c++ boolean mingw operator-precedence mingw32


【解决方案1】:

根据C++ Operator Precedenceoperator&lt;&lt;的优先级高于operator ||(和operator &amp;&amp;),所以cout &lt;&lt; false || true;会被解释为好像(cout &lt;&lt; false) || true;;你总会得到false 被打印出来。

要解决此问题,您应该添加括号以明确指定优先级,例如cout &lt;&lt; (false || true);.

【讨论】:

  • 啊,好吧。知道了。非常感谢@songyuanyao。
猜你喜欢
  • 2011-09-22
  • 2022-11-24
  • 2012-06-06
  • 1970-01-01
  • 2011-02-25
  • 2015-07-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多