如何检查三个值是全部为0还是全部为1

时间:2013-01-01 03:31:25

标签: c++

有3个整数变量,其值可以是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&amp;的值。 c在上面的代码中强加了,因为我把它作为一个简单的例子。 if语句不是要检查是否a,b&amp; c都是平等的。检查它们是否都是0或1个整数值(不是布尔值)。

6 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分: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;
}

答案 2 :(得分: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;
}

答案 3 :(得分: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;
}

答案 4 :(得分:0)

更通用的解决方案:~(~(a ^ b) ^ c)。基于a XNOR b确保两者都为零或一。

的想法

答案 5 :(得分: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;
}
相关问题