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 "等于零!";
else if (compare < 0)
return "小于零!";
else
return "大于零!";
}
}输出结果
这将产生以下输出-
Short Value = 1 Sign (Short Value) = 大于零! Int32 value = 20 Sign (Short Value) = 大于零! Long value = -3545465777 Sign (Long Value) = 小于零!
让我们来看另一个实现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 "等于零!";
else if (compare < 0)
return "小于零!";
else
return "大于零!";
}
}输出结果
这将产生以下输出-
Decimal Value = 20 Sign (Decimal Value) = 大于零! Double value = -35.252 Sign (Double Value) = 小于零!