2014-10-27 166 views
0

我知道如果你的bool函数只打印出一些文本,有两种打印输出的方法。一个是非常简单的,就像这样:用cout打印出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和布尔在同一行中的一行内打印出一些“信息”,但下面的解决方案不会做的伎俩。那有什么问题?

cout << function(a) ? "Equal" : "Not equal"; 

我得到的函数调用的函数将始终返回true,这是相当奇怪的通知。

+4

运算符优先级...'COUT <<(函数(一) “平等”: “不等于”);'另外,**打开编译器警告。** – 2014-10-27 20:45:24

+0

运算符优先级。 – 2014-10-27 20:46:43

+0

@TheParam有。他解释了其中一个。 – 2014-10-27 20:49:46

回答

2

尝试

cout << (function(a) ? "Equal" : "Not equal"); 
+0

谢谢:)它工作完美,忘了( ) – Greg 2014-10-27 20:51:34

4

取决于你的编译器,它可能会告诉究竟是什么问题的警告。

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";。这返回“Equal”(或“Not Equal”,它不重要),导致后续的“表达式结果未使用”警告。

2

我不确定这是你的意思,甚至需要但你有没有考虑使用std::boolalpha

std::cout << function(5) << ' ' << function(6) << std::endl; 
std::cout << std::boolalpha << std::function(5) << ' ' << function(6) << std::endl; 

输出:

1 0 
true false 

http://en.cppreference.com/w/cpp/io/manip/boolalpha