Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

แสดงค่าสัมบูรณ์ (Absolute Value) ใน C#

การหาค่าสัมบูรณ์ (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