การหาค่าสัมบูรณ์ (Absolute Value) ใน C#
ใช้ Static Method Math.Abs() รองรับทุก Numeric Type (int, long, float, double, decimal, sbyte, short)
ตัวอย่างพื้นฐาน
using System;
class Program
{
static void Main()
{
int val1 = 77;
int val2 = -88;
Console.WriteLine("Before: " + val1 + ", " + val2); // 77, -88
int abs1 = Math.Abs(val1);
int abs2 = Math.Abs(val2);
Console.WriteLine("After: " + abs1 + ", " + abs2); // 77, 88
}
}
ผลลัพธ์
Before: 77, -88
After: 77, 88
Overloads ของ Math.Abs
| Signature | คำอธิบาย |
|---|---|
Abs(Decimal) | Decimal |
Abs(Double) | Double |
Abs(Int16) | Short |
Abs(Int32) | Int |
Abs(Int64) | Long |
Abs(SByte) | Signed Byte |
Abs(Single) | Float |
กรณีพิเศษ: Int32.MinValue
int min = int.MinValue; // -2,147,483,648
// Math.Abs(min) โยน OverflowException เพราะ MaxValue = 2,147,483,647
// แก้: ใช้ long หรือ checked/unchecked context
long absMin = Math.Abs((long)min); // 2,147,483,648
ฟังก์ชันคณิตศาสตร์ Math อื่นๆ ที่น่าสนใจ
Math.Max/Min- หาค่ามาก/น้อยสุดMath.Sqrt- รากที่สองMath.Pow- ยกกำลังMath.Round/Floor/Ceiling/Truncate- ปัดเศษMath.Sign- คืน -1, 0, 1