I'm working on a homework assignment, and one little part has me stuck. I get an 8 character phrase from the user, convert the chars to int pairs based on a telephone keypad, then test the int pairs for nearness to each other. No pair can be closer than 5 to another pair. For instance, 24 28 45 51 is invalid because 24 and 28 are only 4 apart. Here's the part of my code that tests for nearness:
1 2 3 4 5 6 7
if(abs(one - two <= 4) || abs(one - three <= 4) ||
abs(one - four <= 4) || abs(two - three <= 4) ||
abs(two - four <= 4) || abs(three - four <= 4))
{
closePairs = true;
}
If true, I set a bool. My problem is that it evaluates to true even if there are no pairs too close together! I've run the debugger (VS2012), and this is where the problem happens.
Let's assume that 'one' is equal to 1, and 'two' is equal to 5.
abs(one - two <=4)
the expression (two <= 4) is evaluated as false, because 5 is not less or equal to 4.
Which turns the original expression into:
abs(one - 0)
which is:
abs(1)
which is true, because the result of this expression is a non-zero value.
In addition, you're doing the same thing for the other expressions, and the condition is true if any expression is true.