Conditional logic / Rock Paper Scissors / not evaluating to False

Hi there,

I’m working on the Rock Paper Scissors Lizard Spock challenge. I got the Rock Paper Scissors part to work fine, so to expand to 5 items, I updated my logic to include some or operators in one half of the && comparison in the else if statement.

For example:

  else if ((computer != 3 || computer !=4) && user == 2) {

    std::cout << "You won!\n";

  }

The way I understand the != operator to work is to check for inequality, so if the computer has selected either 3 or 4 and the user selected 2, I expect the first parentheses to evaluate to False (because the computer has selected either 3 OR 4), and the second condition to be true (because the user has selected 2). This should mean the whole statement is false because the && operator needs both conditions to be True.

However when I run this, when the user == 2 and the computer selects 3 or 4, the code still evaluates to True, despite the computer having selected either 3 or 4.

Any idea where I’m going wrong here?

Thanks

The not equal returns true if the value on it’s left is not equal to the value on its right, and the or returns true if the condition on its left or right is true.

Since you said the computer chose either 3 or 4, lets plug 4 into the equation:

computer = 4
(computer != 3 || computer !=4 )

(4 != 3 || 4 != 4)
    \          \
4 isn't 3   however 4 is 4  
so true        so false

(true || false) or returns true if either is true
                 so this statement is true

As you can see a value of 4 makes the parenthesis true, and doing the same thing with 3 is also true. Since != is only false if the values on its right is equal to the value on its left, and you used an || there is no way the parenthesis can evaluate to false, since computer can’t be both 3 and 4.

Since the parenthesis will always be true the and will make no difference and the if might as well be written as:

else if (user == 2) {   }

Since you are wanting the first parenthesis to evaluate to true only if the computer chooses 3 or 4, you’ll need to rethink your operators a little. Personally I wouldn’t even use a != though you certainly can.

Spoiler alert
if (!(computer == 3 || computer == 4) && user == 2) {   }
1 Like

Thank you so much @8-bit-gaming for the detailed reply, I can see where I was going wrong now. I think I misunderstood the || operator returning true if either condition is true.

1 Like