我如何检查一个数字是正的或负的c# ?


num < 0 // number is negative

bool positive = number > 0;
bool negative = number < 0;

if (num < 0) {
  //negative
}
if (num > 0) {
  //positive
}
if (num == 0) {
  //neither positive or negative,
}

或者使用else if


过分了!

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);
    }
}

你们这些年轻人,还有你们喜欢的"不到"标志。

在我的时代,我们必须使用Math.abs(num) != num //number是负的!


的数学。符号法是一种方法。它将返回-1表示负数,1表示正数,0表示等于0(即0没有符号)。如果双精度变量和单精度变量等于NaN,则会引发异常(ArithmeticException)。


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
}

对于32位有符号整数,例如System。Int32,也就是c#中的int:

bool isNegative = (num & (1 << 31)) != 0;

当然没有人给出正确答案,

num != 0   // num is positive *or* negative!

    public static bool IsPositive<T>(T value)
        where T : struct, IComparable<T>
    {
        return value.CompareTo(default(T)) > 0;
    }

public static bool IsNegative<T>(T value)
   where T : struct, IComparable<T>
{
    return value.CompareTo(default(T)) < 0;
}

你只需要比较是否值和它的绝对值相等:

if (value == Math.abs(value))
    return "Positif"
else return "Negatif"

本地程序员版本。行为对于小端系统是正确的。

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);
   }
   return result;
}

永远不要用这个。


这是行业标准:

int is_negative(float num)
{
  char *p = (char*) malloc(20);
  sprintf(p, "%f", num);
  return p[0] == '-';
}

bool isNegative(int n) {
  int i;
  for (i = 0; i <= Int32.MaxValue; i++) {
    if (n == i) 
      return false;
  }
  return true;
}

该代码利用SIMD指令来提高性能。

public static bool IsPositive(int n)
{
  var v = new Vector<int>(n);
  var result = Vector.GreaterThanAll(v, Vector<int>.Zero);
  return result;
}

第一个参数存储在EAX寄存器和结果中。

function IsNegative(ANum: Integer): LongBool; assembler;
asm
   and eax, $80000000
end;