C#中的Math.Abs()方法
C#中的Math.Abs()方法用于返回C#中指定数字的绝对值。此指定的数字可以是十进制,双精度,16位有符号整数等。
示例
现在让我们看一个示例,该示例实现Math.abs()方法以返回双数的绝对值-
using System; class Demo { public static void Main(){ Double val1 = 30.40; Double val2 = Double.MinValue; Double val3 = Double.MaxValue; Console.WriteLine("Absolute value of {0} : {1}", val1, Math.Abs(val1)); Console.WriteLine("Absolute value of {0} : {1}", val2, Math.Abs(val2)); Console.WriteLine("Absolute value of {0} : {1}", val3, Math.Abs(val3)); } }
输出结果
这将产生以下输出-
Absolute value of 30.4 : 30.4 Absolute value of -1.79769313486232E+308 : 1.79769313486232E+308 Absolute value of 1.79769313486232E+308 : 1.79769313486232E+308
示例
现在让我们来看另一个示例,该示例实现Math.abs()方法以返回16位带符号整数的绝对值-
using System; class Demo { public static void Main(){ short val1 = -300; short val2 = Int16.MaxValue; short val3 = 0; Console.WriteLine("Absolute value of {0} : {1}", val1, Math.Abs(val1)); Console.WriteLine("Absolute value of {0} : {1}" val2, Math.Abs(val2)); Console.WriteLine("Absolute value of {0} : {1}", val3, Math.Abs(val3)); } }
输出结果
这将产生以下输出-
Absolute value of -300 : 300 Absolute value of 32767 : 32767 Absolute value of 0 : 0