2014-10-27 164 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