Issue
i have been asked to make code that doesen’t have loops and check if first number is close to second number (close means bigger or smaller by one).I tried using huge conditions but i wodered maybe there is an easyer way then do things like this:
if num1 == num2 or num1 == num2 – 1 or num1 == num2 + 1
Solution
Calculate the difference between the 2 numbers, take the absolute value of that (in case num2
is larger than num1
) and compare the result to 1:
abs(num1  num2) <= 1
The advantage of this over OP’s code

Works with floating point numbers. Ex 1 and 1.4 will fail in original code but succeed in this.

Easy to change the definition of “is close to”. Ex, can use 0.5 or 10000000 on the rhs.
Answered By – Johnny Mopp
This Answer collected from stackoverflow, is licensed under cc bysa 2.5 , cc bysa 3.0 and cc bysa 4.0