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


当前回答

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

其他回答

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

或者使用else if

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

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

永远不要用这个。

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

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

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

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

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