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


当前回答

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

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

其他回答

public static bool IsNegative<T>(T value)
   where T : struct, IComparable<T>
{
    return value.CompareTo(default(T)) < 0;
}
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
}

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

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

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

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

这是行业标准:

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