【问题标题】:How do I check if a number is positive or negative in C#?如何在 C# 中检查数字是正数还是负数?
【发布时间】:2010-11-04 17:23:49
【问题描述】:

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

【问题讨论】:

  • 有用的问题。

标签: c#


【解决方案1】:
bool positive = number > 0;
bool negative = number < 0;

【讨论】:

  • 可怜的旧负零呢?!
  • @SimonFischer 肯定有数学分支、计算机科学以及常规科学使用负零和正零。例如,化学家和物理学家有时会使用 -0 来表示负数并四舍五入为零。定义仅在上下文中有意义。当您将所学的数学定义视为真正具有普遍性时,您可能会最终陷入错误的不同数学环境中。
  • 我来找同样的东西。看到这个,我就像“哦!”期待别的东西。为什么我没有想到这一点。压力人!压力!大声笑
【解决方案2】:

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

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

【讨论】:

  • 不,OP询问is positive or is negative不是is (positive or negative)
  • 0 仍然是积极的
  • @T.Todua 我相信那是个笑话。
  • 干得好先生
【解决方案3】:

杀戮!

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

【讨论】:

  • 在内部,它应该使用SignDeterminatorFactory 实例化一个实现ISignDeterminator 的类。
  • 不完整:你也应该检查 IsNaN() ;)
  • @slashmais: 在int?!你在 C# 的哪个神奇领域工作?
  • 对于 .NET 4.0,您应该添加 IsImaginary
  • 你应该在你的代码中添加 注释,使它变得更可靠、一致、体面、可访问、稳定、健壮、可靠、安全和清晰。
【解决方案4】:

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

【讨论】:

  • 哇不知道这存在。NaN 会发生什么?
  • @Tanmoy:在这种情况下,看起来它会抛出an exception
  • 但是他也必须检查 Math.Sign 的结果是正数还是负数!他也使用 Math.Sign 吗? ;)
  • @AndyC:我很喜欢这个幽默,但他应该对Math.Sign 的返回值进行相等比较(因为它明确定义了可能的返回值。)
  • 我没想到会在这个问题下面找到有用的答案,但这实际上是我正在寻找的。谢谢。
【解决方案5】:
num < 0 // number is negative

【讨论】:

  • 我认为这是一个初学者,我们应该尝试帮助。一旦你学会了正确的方法——检查这个错误的方法thedailywtf.com/Articles/…
  • 起初我不敢相信主页上的问题,然后我来到这里...... :) 这个人并不孤单......哦,亲爱的:)
【解决方案6】:

这是行业标准:

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

【讨论】:

  • 我试过了。我的程序最终内存不足。你的代码可能有泄漏吗?
  • @Will,很好地发现了这个非常模糊的泄漏!尽管我不赞成您更改原始海报介绍性句子的含义。我仍然认为将其称为行业标准是正确的。因此,为了保持这个答案的精神,关于原始海报,我已经恢复了你的编辑,好吗?
  • @Will,我真的需要说明关于原始帖子和我的 cmets 的显而易见的事情,而你的则没有? (剧透:它与讽刺有关,而你的则不是,这意味着你已经扼杀了这里存在的坏笑话 - 或者你真的认为这个答案应该被认真对待吗??)
  • 我是认真的;讽刺并不明显,这会使新用户和非母语人士感到困惑。如果这不是一个严肃的答案,我会恢复我的编辑并将其标记为不是答案。
  • 我们去,恢复,标记,和downvoted。我不知道这是个玩笑。
【解决方案7】:

你们这些年轻人和你们喜欢的小于号。

在我以前,我们不得不使用Math.abs(num) != num //number is negative

【讨论】:

  • (如果不是很明显,这是为了幽默)
  • @Eric: 不,因为无论传入什么类型(Int16Int32Int64),如果numMinValue,它都会抛出OverflowException。浮点值的结果更糟,它们也可能是NaN,因为NaN != NaN
【解决方案8】:
    public static bool IsPositive<T>(T value)
        where T : struct, IComparable<T>
    {
        return value.CompareTo(default(T)) > 0;
    }

【讨论】:

    【解决方案9】:

    本地程序员的版本。小端系统的行为是正确的。

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

    永远不要使用它。

    【讨论】:

    • “永远不要使用这个”?但它是企业级代码,非常适合企业软件!不过,您缺少IsPositiveCheckerIsPositiveCheckerInterfaceIsPositiveCheckerFactoryIsPositiveCheckerFactoryInterface
    • 刚刚在我的 Hello World 控制台应用程序中使用了这个。 10/10 会再做一次。
    • 您缺少一组括号,因为“&”的优先级低于“==”,因此您应该使用result = (Marshal.ReadByte(memory, 3) &amp; 0x80) == 0;。此外,您应该在最后的某处有一个return result;,这样它实际上会返回结果。
    【解决方案10】:
    if (num < 0) {
      //negative
    }
    if (num > 0) {
      //positive
    }
    if (num == 0) {
      //neither positive or negative,
    }
    

    或者使用“else ifs”

    【讨论】:

      【解决方案11】:

      对于 32 位有符号整数,例如 System.Int32,在 C# 中又名 int

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

      【讨论】:

        【解决方案12】:

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

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

        【讨论】:

          【解决方案13】:
          bool isNegative(int n) {
            int i;
            for (i = 0; i <= Int32.MaxValue; i++) {
              if (n == i) 
                return false;
            }
            return true;
          }
          

          【讨论】:

            【解决方案14】:
            public static bool IsNegative<T>(T value)
               where T : struct, IComparable<T>
            {
                return value.CompareTo(default(T)) < 0;
            }
            

            【讨论】:

              【解决方案15】:
              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
              }
              

              【讨论】:

                【解决方案16】:

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

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

                【讨论】:

                  【解决方案17】:

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

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

                  【讨论】:

                    猜你喜欢
                    • 1970-01-01
                    • 2011-04-30
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 2023-03-18
                    • 1970-01-01
                    • 2012-05-12
                    • 2014-03-28
                    相关资源
                    最近更新 更多