2013-01-01 37 views
2

有3個整型變量可以具有值0或1.如果全部爲0或全部爲1,則打印特定語句。對於所有其他值的組合可以打印另一個語句。如何檢查三個值全部是0還是全部1

我試過下面的工作。有沒有更好的方法來編寫if語句?

#include <iostream> 
using namespace std; 

int main() 
{ 
    int a, b, c; 
    cin >> a >> b >> c; 

    if(!(a != 0 && b != 0 && c != 0) && !(a == 0 && b == 0 && c == 0)) 
    { 
     cout << "a, b or c have mixed values of 1 and 0" << endl; 
    } 
    else 
    { 
     cout << "All of a, b and c are either 1 or 0" << endl; 
    } 

    system("pause"); 
    return 0; 
} 

對不起引起了一些混淆。實際上,在上面的代碼中,沒有對a,b & c的值進行檢查,因爲我把它作爲一個簡單的例子。 if語句不是檢查a,b是否全部相等。它是檢查它們全部是0還是1整數值(不是布爾值)。

+0

'cin.get()'將在輸入行的末尾獲取回車值,其中值被捕獲。你需要另一個捕獲第二個CR。只需從命令窗口/終端運行它。 – KayEss

+3

你的問題說你的整型變量_all可以有值0或1_。這是否意味着,他們只能是0或1?如果是的話,爲什麼你在你的代碼中用10進行初始化? – jogojapan

+0

如果我瞭解您最近的修改,他們實際上可以具有0或1以外的值,對嗎? – jogojapan

回答

7
if(((a & b & c) ==1) || ((a | b | c) == 0)) 
+0

這是不正確的,因爲&是按位並且變量不是布爾值。 –

+0

實際上,它是正確的,因爲OP表示a,b和c只能有0或1。 – paulsm4

+0

@MatthewLundberg只要所有值都爲0或1,它就會工作。 – Matthew

5

在您的代碼中,用戶輸入的值沒有限制。

如果你只是想看看是否所有值都彼此相等,你可以這樣做:

if (a == b && b == c) 
{ 
    cout << "A, B, and C are all equal" << endl; 
} 
else 
{ 
    cout << "A, B, and C contain different values" << endl; 
} 
3
#include<iostream> 
using namespace std; 

int main() 
{ 
int a = 10, b = 10, c = 10; 
cin >> a >> b >> c; 

if((a == 0 && b == 0 && c == 0)||(a==1&&b==1&&c==1)) 
{ 
     cout << "All of a, b and c are either 1 or 0" << endl; 

} 
else 
{ 
cout << "a, b or c have mixed values of 1 and 0" << endl; 
} 

system("pause"); 
return 0; 
} 
1
if((b!=c) || (a^b)) 
{ 
    std::cout << "a, b or c have mixed values of 1 and 0" << std::endl; 
} 
else 
{ 
    std::cout << "All of a, b and c are either 1 or 0" << std::endl; 
} 

另一種方式效率較低的方式:

if((a!=0) + (b!=0) - 2 * (c!=0) == 0) 
{ 
    cout << "All of a, b and c are either 1 or 0" << endl; 
} 
else 
{ 
    cout << "a, b or c have mixed values of 1 and 0" << endl; 
} 
0

更通用的解決方案:~(~(a^b)^c)。基於a XNOR b確保兩者都爲零或一的想法。

0

前提是你正在使用C++ 11,你可以實現你與可變參數模板查找的內容,例如:

template <typename T, typename U> 
bool allequal(const T &t, const U &u) { 
    return t == u; 
} 

template <typename T, typename U, typename... Args> 
bool allequal(const T &t, const U &u, Args const &... args) { 
    return (t == u) && allequal(u, args...); 
} 

而且你可以在你的代碼中調用它像這樣:

if (allequal(a,b,c,0) || allequal(a,b,c,1)) 
{ 
    cout << "All of a, b and c are either 1 or 0" << endl; 
} 
相關問題