C# 中的 Math.Sign() 方法


C# 中的 Math.Sign() 方法用于返回表示数字符号的整数。

方法

Math.Sign() 重载了以下方法 −

Math.Sign(Int16)
Math.Sign(Int32)
Math.Sign(Int64)
Math.Sign(SByte)
Math.Sign(Single)
Math.Sign(Decimal)
Math.Sign(Double)

示例

现在我们来看一个实现 Math.Sign() 方法的示例 −

using System;
public class Demo {
   public static void Main(){
      short val1 = 1;
      int val2 = 20;
      long val3 = -3545465777;
      Console.WriteLine("Short Value = " + val1);
      Console.WriteLine("Sign (Short Value) = " + getSign(Math.Sign(val1)));
      Console.WriteLine("Int32 value = " + val2);
      Console.WriteLine("Sign (Short Value) = " + getSign(Math.Sign(val2)));
      Console.WriteLine("Long value = " + val3);
      Console.WriteLine("Sign (Long Value) = " + getSign(Math.Sign(val3)));
   }
   public static String getSign(int compare){
      if (compare == 0)
         return "Equal to zero!";
      else if (compare < 0)
         return "Less than zero!";
      else
         return "Greater than zero!";
   }
}

输出

这将产生以下输出 −

Short Value = 1
Sign (Short Value) = Greater than zero!
Int32 value = 20
Sign (Short Value) = Greater than zero!
Long value = -3545465777
Sign (Long Value) = Less than zero!

示例

让我们再看一个实现 Math.Sign() 方法的示例 −

using System;
public class Demo {
   public static void Main(){
      Decimal val1 = 20m;
      Double val2 = -35.252d;
      Console.WriteLine("Decimal Value = " + val1);
      Console.WriteLine("Sign (Decimal Value) = " + getSign(Math.Sign(val1)));
      Console.WriteLine("Double value = " + val2);
      Console.WriteLine("Sign (Double Value) = " + getSign(Math.Sign(val2)));
   }
   public static String getSign(int compare){
      if (compare == 0)
         return "Equal to zero!";
      else if (compare < 0)
         return "Less than zero!";
      else
         return "Greater than zero!";
   }
}

输出

这将产生以下输出 −

Decimal Value = 20
Sign (Decimal Value) = Greater than zero!
Double value = -35.252
Sign (Double Value) = Less than zero!

更新时间: 2019 年 11 月 8 日

904 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告