0

I have a list of numbers that may be positive/negative/zero, and I want to compare them to exactly -1, 0, 1 without if-then-else statements. Is that possible by setting non-zero numbers to 1, but leaving it's original sign either negative/positive?

EG. Setting -0.6 to -1, and setting 0.8 to 1, and leaving 0 as 0.

MikeB
  • 1
  • 2
    "_I want to compare them to exactly -1, 0, 1 without if-then-else statements_": Have you tested whether the compiler doesn't make this optimization by itself anyway? – user17732522 May 10 '22 at 15:43
  • 2
    You are going to need to perform a boolean test of *some* kind; what's the problem with `if-then-else` ? – Mark Benningfield May 10 '22 at 15:44
  • In this list of numbers, do the number get larger than `-1` or `1`, i.e. will numbers like -6.5 or 5 show up in the list – NathanOliver May 10 '22 at 15:44
  • `x = (x > 0) - (x < 0);`? It's the shortest way to spell it I know. – HolyBlackCat May 10 '22 at 15:45
  • C or C++? They're different languages and the result would be very different. Choose only one language – phuclv May 10 '22 at 15:45
  • 1
    You should look for signum function. C++ standard has something like copysign. Various methods exists (like what @HolyBlackCat mentioned) – Jakub Piskorz May 10 '22 at 15:45
  • 3
    [Is there a standard sign function (signum, sgn) in C/C++?](https://stackoverflow.com/q/1903954/995714) – phuclv May 10 '22 at 15:46

0 Answers0