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


当前回答

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

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

其他回答

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

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

过分了!

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);
    }
}
num < 0 // number is negative

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

num != 0   // num is positive *or* negative!
bool positive = number > 0;
bool negative = number < 0;