我知道如果你的 bool 函数只打印出一些文本,有两种打印结果的方法。一个非常简单,像这样:
#include <iostream>
using namespace std;
bool function(int x)
{
int y=5;
return x==y;
}
int main(void)
{
int a;
cin >> a;
if(function(a))
cout << "Equal to 5";
else
cout << "Not equal to 5";
}
我曾经知道其他方法可以在同一行中使用 cout 和 bool 在一行中打印出一些“消息”,但以下解决方案无法解决问题。这有什么问题?
cout << function(a) ? "Equal" : "Not equal";
我收到通知,调用函数的函数将始终返回 true,这很奇怪。
最佳答案
根据您的编译器,它可能会发出警告,准确说明问题所在。
main.cpp:15:21: warning: operator '?:' has lower precedence than '<<'; '<<' will be evaluated first [-Wparentheses]
cout << function(a) ? "Equal" : "Not equal";
~~~~~~~~~~~~~~~~~~~ ^
main.cpp:15:21: note: place parentheses around the '<<' expression to silence this warning
cout << function(a) ? "Equal" : "Not equal";
^
( )
main.cpp:15:21: note: place parentheses around the '?:' expression to evaluate it first
cout << function(a) ? "Equal" : "Not equal";
main.cpp:15:26: warning: expression result unused [-Wunused-value]
cout << function(a) ? "Equal" : "Not equal";
作为@The Paramagnetic Croissant说,将其括在括号中。
cout << (function(a) ? "Equal" : "Not equal");
根据 @WhozCraig's comment , 一个解释是顺序。正如警告所说,<<
首先进行评估,结果为 (cout << function(a)) ? "Equal : "Not Equal";
.这将返回“等于”(或“不等于”,无关紧要),从而导致随后的“表达式结果未使用”警告。
关于c++ - 用 cout 打印出 bool 选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26596509/