Can you use 2 or more OR conditions in an if statement?
You need to code your tests differently:
if (number==1 || number==2 || number==3) {
cout << "Your number was 1, 2, or 3." << endl;
}
else if (number==4 || number==5 || number==6) {
cout << "Your number was 4, 5, or 6." << endl;
}
else {
cout << "Your number was above 6." << endl;
}
The way you were doing it, the first condition was being interpreted as if it were written like this
if ( (number == 1) || 2 || 3 ) {
The logical or operator (||
) is defined to evaluate to a true value if the left side is true or if the left side is false and the right side is true. Since 2
is a true value (as is 3
), the expression evaluates to true regardless of the value of number
.
While you can (as others have shown) re-write your tests to allow what you want, I think it's also worth considering a couple of alternatives. One would be a switch statement:
switch (number) {
case 1:
case 2:
case 3:
cout << "Your number was 1, 2, or 3." << endl;
break;
case 4:
case 5:
case 6:
cout << "Your number was 4, 5, or 6." << endl;
break;
default:
cout << "Your number was above 6." << endl;
}
Personally, I'd probably do something like this though:
char const *msgs[] = {
"Your number was 1, 2, or 3.\n",
"Your number was 4, 5, or 6.\n"
};
if (number < 1 || number > 6)
std::cout << "Your number was outside the range 1..6.\n";
else
std::cout << msgs[(number-1)/3];
Note that as it stands right now, your code says that 0 and all negative numbers are greater than 6. I've left this alone in the first example, but fixed it in the second.