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

เมธอด Double.IsNegativeInfinity() ใน C# : ตรวจสอบค่าลบอันันต์

เมธอด Double.IsNegativeInfinity() ใน C# ใช้ตรวจสอบว่าค่า double ที่ระบุประเมินผลเป็น ลบอันันต์ (negative infinity) หรือไม่ คืนค่า true หากเป็นลบอันันต์ มิฉะนั้นคืน false

รูปแบบไวยากรณ์ (Syntax)

public static bool IsNegativeInfinity(double val);

val : ค่าทศนิยม double precision ที่ต้องการตรวจสอบ

ตัวอย่างที่ 1: ตรวจสอบค่า NaN (Not a Number)

using System;

public class Demo
{
    public static void Main()
    {
        double d = 0.0 / 0; // NaN
        
        Console.WriteLine("Double Value = " + d);
        Console.WriteLine("HashCode of Double Value = " + d.GetHashCode());
        TypeCode type = d.GetTypeCode();
        Console.WriteLine("TypeCode of Double Value = " + type);
        Console.WriteLine("Positive Infinity? = " + Double.IsInfinity(d));
        Console.WriteLine("Check whether the specified value is NaN? = " + Double.IsNaN(d));
        Console.WriteLine("Does the value evaluate to negative infinity? = " + Double.IsNegativeInfinity(d));
    }
}

ผลลัพธ์

Double Value = NaN
HashCode of Double Value = -524288
TypeCode of Double Value = Double
Positive Infinity? = False
Check whether the specified value is NaN? = True
Does the value evaluate to negative infinity? = False

ตัวอย่างที่ 2: ตรวจสอบค่าลบอันันต์จริง

using System;

public class Demo
{
    public static void Main()
    {
        double d = -1.0 / 0.0; // Negative Infinity
        
        Console.WriteLine("Double Value = " + d);
        Console.WriteLine("HashCode of Double Value = " + d.GetHashCode());
        TypeCode type = d.GetTypeCode();
        Console.WriteLine("TypeCode of Double Value = " + type);
        Console.WriteLine("Positive Infinity? = " + Double.IsInfinity(d));
        Console.WriteLine("Check whether the specified value is NaN? = " + Double.IsNaN(d));
        Console.WriteLine("Does the value evaluate to negative infinity? = " + Double.IsNegativeInfinity(d));
    }
}

ผลลัพธ์

Double Value = -∞
HashCode of Double Value = -1048576
TypeCode of Double Value = Double
Positive Infinity? = True
Check whether the specified value is NaN? = False
Does the value evaluate to negative infinity? = True

เมธอดเกี่ยวข้องสำหรับ double

เมธอด วัตถุประสงค์
Double.IsInfinity(d) ตรวจสอบว่เป็นบวกอันันต์หรือลบอันันต์
Double.IsPositiveInfinity(d) ตรวจสอบเฉพาะบวกอันันต์
Double.IsNegativeInfinity(d) ตรวจสอบเฉพาะลบอันันต์
Double.IsNaN(d) ตรวจสอบว่าเป็น Not a Number (0/0, sqrt(-1), ฯลฯ)

สรุป

  • การหารด้วยศูนย์ใน double จะได้ Infinity (ไม่ใช่ exception เหมือน integer)
  • 1.0/0.0 = PositiveInfinity, -1.0/0.0 = NegativeInfinity
  • 0.0/0.0 = NaN
  • ใช้เมธอดเหล่านี้ตรวจสอบก่อนการคำนวณต่อเพื่อป้องกันข้อผิดพลาด