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


当前回答

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

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

其他回答

这是行业标准:

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

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

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

过分了!

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