¿Cómo puedo comprobar si un número es positivo o negativo en C#?


¿Cómo puedo comprobar si un número es positivo o negativo en C#?

 192
c#
Author: Tot Zam, 2010-11-04

16 answers

bool positive = number > 0;
bool negative = number < 0;
 186
Author: Simon Fischer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-30 16:10:19

Por supuesto que nadie ha dado la respuesta correcta,

num != 0   // num is positive *or* negative!
 170
Author: tjm,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-20 10:55:44

OVERKILL!

public static class AwesomeExtensions
{
    public static bool IsPositive(this int number)
    {
        return number > 0;
    }

    public static bool IsNegative(this int number)
    {
        return number < 0;
    }

    public static bool IsZero(this int number)
    {
        return number == 0;
    }

    public static bool IsAwesome(this int number)
    {
        return IsNegative(number) && IsPositive(number) && IsZero(number);
    }
}
 79
Author: hunter,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-11-04 18:27:43
num < 0 // number is negative
 56
Author: Lou Franco,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-11-04 17:24:23

La Matemática.Sign method es un camino a seguir. Devolverá -1 para números negativos, 1 para números positivos y 0 para valores iguales a cero (es decir, cero no tiene ningún signo). Las variables de precisión dobles y simples causarán una excepción (ArithmeticException) que se lanzará si son iguales a NaN.

 50
Author: gnovice,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-11-04 19:19:24

Este es el estándar de la industria:

int is_negative(float num)
{
  char *p = (char*) malloc(20);
  sprintf(p, "%f", num);
  return p[0] == '-';
}
 22
Author: portforwardpodcast,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-20 23:04:44

Usted youngins y su fantasía menos que signos.

En mi época teníamos que usar Math.abs(num) != num //number is negative!

 19
Author: Powerlord,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-11-04 17:30:43
    public static bool IsPositive<T>(T value)
        where T : struct, IComparable<T>
    {
        return value.CompareTo(default(T)) > 0;
    }
 9
Author: Igor Goroshko,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-15 12:17:57

Versión nativa del programador. El comportamiento es correcto para los sistemas little-endian.

bool IsPositive(int number)
{
   bool result = false;
   IntPtr memory = IntPtr.Zero;
   try
   {
       memory = Marshal.AllocHGlobal(4);
       if (memory == IntPtr.Zero)
           throw new OutOfMemoryException();

       Marshal.WriteInt32(memory, number);

       result = Marshal.ReadByte(memory, 3) & 0x80 == 0;
   }
   finally
   {
       if (memory != IntPtr.Zero)
           Marshal.FreeHGlobal(memory);
   }
}

Nunca use esto.

 7
Author: Polynomial,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-08 15:06:55
if (num < 0) {
  //negative
}
if (num > 0) {
  //positive
}
if (num == 0) {
  //neither positive or negative,
}

O use "else ifs"

 6
Author: Barrie Reader,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-11-04 17:27:16

Para un entero con signo de 32 bits, como System.Int32, también conocido como int en C#:

bool isNegative = (num & (1 << 31)) != 0;
 6
Author: Drew Noakes,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-12-13 18:35:17
public static bool IsNegative<T>(T value)
   where T : struct, IComparable<T>
{
    return value.CompareTo(default(T)) < 0;
}
 5
Author: jero2rome,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-15 12:58:28

Solo tiene que comparar si el valor y su valor absoluto son iguales:

if (value == Math.abs(value))
    return "Positif"
else return "Negatif"
 4
Author: Issam Ben Amara,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-18 15:52:25
bool isNegative(int n) {
  int i;
  for (i = 0; i <= Int32.MaxValue; i++) {
    if (n == i) 
      return false;
  }
  return true;
}
 4
Author: gberger,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-18 20:06:09
int j = num * -1;

if (j - num  == j)
{
     // Num is equal to zero
}
else if (j < i)
{
      // Num is positive
}
else if (j > i) 
{
     // Num is negative
}
 3
Author: Jla,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-11-09 10:29:28

Este código aprovecha las instrucciones SIMD para mejorar el rendimiento.

public static bool IsPositive(int n)
{
  var v = new Vector<int>(n);
  var result = Vector.GreaterThanAll(v, Vector<int>.Zero);
  return result;
}
 0
Author: Michal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-29 19:40:12