... "If the number is exactly equal, or equal+1 or equal-1".
Your problem statement seems to assume integer operations: "If the number is exactly equal, or exactly equal+1 or exactly equal-1." The tests given by ikegami here are not quite equivalent to your OPed test if the numbers are not integers: (update: ikegami already assumed integers in his reply, but the following examples are still pertinent.) | If the numbers are not integers:
Remember that Perl numbers are essentially floating-point doubles. This may introduce some twists and pitfalls. (Update: Certain combinations of operations may produce a number like 2.00000000000000123 that may appear, in certain circumstances, to be an integer, but isn't. See What Every Computer Scientist Should Know About Floating-Point Arithmetic.) One way to force integer operations is with the integer pragma:c:\@Work\Perl\monks>perl -wMstrict -le "my $x = 2; my $y = 2.00000000000000123; print qq{$x $y}; ;; if ($x == $y or $x == $y-1 or $x == $y+1) { print 'in exact range'; } if ($y-1 <= $x && $x <= $y+1) { print 'in <= range'; } if (abs($y-$x) <= 1) { print 'in abs range'; } " 2 2 in <= range in abs range
c:\@Work\Perl\monks>perl -wMstrict -le "use integer; ;; my $x = 2; my $y = 2.00000000000000123; print qq{$x $y}; ;; if ($x == $y or $x == $y-1 or $x == $y+1) { print 'in exact range'; } if ($y-1 <= $x && $x <= $y+1) { print 'in <= range'; } if (abs($y-$x) <= 1) { print 'in abs range'; } " 2 2 in exact range in <= range in abs range
Update: Changed both code examples to use the floating-point number 2.00000000000000123 (vice 2.5) for $y.
Give a man a fish: <%-{-{-{-<
In reply to Re: IF condition with a range (updated)
by AnomalousMonk
in thread IF condition with a range
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |