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


当前回答

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

其他回答

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);
    }
}
bool positive = number > 0;
bool negative = number < 0;

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

bool isNegative = (num & (1 << 31)) != 0;
public static bool IsNegative<T>(T value)
   where T : struct, IComparable<T>
{
    return value.CompareTo(default(T)) < 0;
}