如何检查C#中的数字是正数还是负数?

时间:2010-11-04 17:23:50

标签: c#

如何在C#中检查数字是正数还是负数?

17 个答案:

答案 0 :(得分:201)

bool positive = number > 0;
bool negative = number < 0;

答案 1 :(得分:173)

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

num != 0   // num is positive *or* negative!

答案 2 :(得分:81)

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

答案 3 :(得分:56)

num < 0 // number is negative

答案 4 :(得分:55)

Math.Sign method是一种可行的方法。对于负数,它将返回-1,对于正数,它将返回1,对于等于零的值,它将返回0(即,零没有符号)。如果双精度变量和单精度变量等于NaN,则会引发异常(ArithmeticException)。

答案 5 :(得分:24)

这是行业标准:

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

答案 6 :(得分:19)

你的年轻人和你的幻想少于标志。

回到我的日子,我们不得不使用Math.abs(num) != num //number is negative

答案 7 :(得分:10)

    public static bool IsPositive<T>(T value)
        where T : struct, IComparable<T>
    {
        return value.CompareTo(default(T)) > 0;
    }

答案 8 :(得分:8)

本机程序员的版本。对于小端系统,行为是正确的。

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

不要使用它。

答案 9 :(得分:6)

if (num < 0) {
  //negative
}
if (num > 0) {
  //positive
}
if (num == 0) {
  //neither positive or negative,
}

或使用“else ifs”

答案 10 :(得分:6)

对于32位有符号整数,例如{#1}},又称C#中的System.Int32

int

答案 11 :(得分:5)

public static bool IsNegative<T>(T value)
   where T : struct, IComparable<T>
{
    return value.CompareTo(default(T)) < 0;
}

答案 12 :(得分:5)

你只需要比较价值&amp;它的绝对值是相等的:

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

答案 13 :(得分:5)

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

答案 14 :(得分:3)

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
}

答案 15 :(得分:1)

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

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

答案 16 :(得分:0)

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

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