How do I check if a number is positive or negative in C#?

前端 未结 17 1405
轻奢々
轻奢々 2020-12-04 05:55

How do I check if a number is positive or negative in C#?

相关标签:
17条回答
  • 2020-12-04 06:09
    if (num < 0) {
      //negative
    }
    if (num > 0) {
      //positive
    }
    if (num == 0) {
      //neither positive or negative,
    }
    

    or use "else ifs"

    0 讨论(0)
  • 2020-12-04 06:09

    For a 32-bit signed integer, such as System.Int32, aka int in C#:

    bool isNegative = (num & (1 << 31)) != 0;
    
    0 讨论(0)
  • 2020-12-04 06:11

    Native programmer's version. Behaviour is correct for little-endian systems.

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

    Do not ever use this.

    0 讨论(0)
  • 2020-12-04 06:11

    This code takes advantage of SIMD instructions to improve performance.

    public static bool IsPositive(int n)
    {
      var v = new Vector<int>(n);
      var result = Vector.GreaterThanAll(v, Vector<int>.Zero);
      return result;
    }
    
    0 讨论(0)
  • 2020-12-04 06:13

    OVERKILL!

    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);
        }
    }
    
    0 讨论(0)
  • 2020-12-04 06:14
    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
    }
    
    0 讨论(0)
提交回复
热议问题