-1

I'm trying to write a code that tells me whether a number is negative/positive, even/odd. For example:

  • given -2 -> e -1,
  • given -3 -> o -1

and so on. The thing is it's working for everything expect negative odd numbers.

Here's the part of the code that's responsible for deciding:

if (number % 2 == 0 && number < 0)
{
    Console.WriteLine("e" + " " + "-1");
}
else if (number % 2 == 0 && number > 0)
{
    Console.WriteLine("e" + " " + "1");
}
else if (number % 2 == 1 && number > 0)
{
    Console.WriteLine("o" + " " + "1");
}
else if (number % 2 == 1 && number < 0)
{
    Console.WriteLine("o" + " " + "-1");
}
else if (number == 0)
{
    Console.WriteLine("0");
}
  • Does this answer your question? [How do I check if a number is positive or negative in C#?](https://stackoverflow.com/questions/4099366/how-do-i-check-if-a-number-is-positive-or-negative-in-c) and https://stackoverflow.com/questions/18818680/testing-if-a-list-of-integer-is-odd-or-even both have information pertaining to your issue. – Trevor Nov 14 '20 at 18:56
  • `if (number == 0) Console.WriteLine("0") else Console.WriteLine($"{(number % 2 == 0 ? 'e' : 'o')} {(number < 0 ? -1 : 1)}")` – Dmitry Bychenko Nov 14 '20 at 20:07

2 Answers2

0

if it is a negative no. it's remainder is going to be negative as well when divided by 2 so :

else if (number % 2 == -1 && number < 0)
{
    Console.WriteLine("o" + " " + "-1");
}

or directly

else if (number % 2 == -1)
Codeek
  • 1,624
  • 1
  • 11
  • 20
0

Remainder computation can vary. In math when we compute

  r = a mod b

we, usually, assume that r in [0 .. |b|) range, i.e. r is non negative. However, in case of modulo arithmetics we can add k * |b| (where k is arbitrary integer) term. For instance

 -5 mod 3 == -8, -5, -2, 1, 4, 7 etc.
                      ^  ^
              C# choice  |
                         Typical math choice: r in [0 .. 3) range

In case of c# implementation we have -2, not 1. So the safe method to test for being odd / even is to compare with 0, not -1, 1:

 if (number == 0) 
   Console.WriteLine("0"); // 0 - special case 
 else 
   Console.WriteLine($"{(number % 2 == 0 ? 'e' : 'o')} {(number < 0 ? -1 : 1)}");

Please, note number % 2 == 0 test bor being even / odd

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215