有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;
}
Run Code Online (Sandbox Code Playgroud)
很抱歉造成了一些混乱.实际上没有检查上面代码中强加的a,b和c的值,因为我把它作为一个简单的例子.if语句不是要检查a,b和c是否全部相等.它是检查它们是否都是0或1个整数值(不是布尔值).
在您的代码中,对用户输入的值没有限制.
如果您只想查看所有值是否彼此相等,您可以执行以下操作:
if (a == b && b == c)
{
cout << "A, B, and C are all equal" << endl;
}
else
{
cout << "A, B, and C contain different values" << endl;
}
Run Code Online (Sandbox Code Playgroud)