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

เมธอด Math.Min() ใน C#

เมธอด Math.Min() ใน C# ใช้คืนค่าที่น้อยกว่าของสองตัวเลขที่ระบุ เมธอดนี้รองรับหลายประเภทข้อมูล เช่น Double, Decimal, Int16, Int32, เป็นต้น

ไวยากรณ์

public static ulong Min (ulong val1, ulong val2); 
public static uint Min (uint val1, uint val2); 
public static ushort Min (ushort val1, ushort val2); 
public static float Min (float val1, float val2); 
public static byte Min (byte val1, byte val2); 
public static long Min (long val1, long val2);

ตัวอย่าง

ตัวอย่างที่ 1: หาค่าต่ำสุดของหลายประเภทข้อมูล

using System; 
public class Demo { 
    public static void Main(){ 
        byte val1 = 10, val2 = 15; 
        decimal val3 = 1000M, val4 = 1500M; 
        double val5 = 15.896745, val6 = 25.676843; 
        short val7 = 20, val8 = 30; 
        Console.WriteLine("Minimum Value from two byte values = " + Math.Min(val1, val2)); 
        Console.WriteLine("Minimum Value from two decimal values = " + Math.Min(val3, val4)); 
        Console.WriteLine("Minimum Value from two double values = " + Math.Min(val5, val6)); 
        Console.WriteLine("Minimum Value from two short values = " + Math.Min(val7, val8)); 
    } 
}

ผลลัพธ์

Minimum Value from two byte values = 10 
Minimum Value from two decimal values = 1000 
Minimum Value from two double values = 15.896745 
Minimum Value from two short values = 20

ตัวอย่างเพิ่มเติม

ตัวอย่างที่ 2: หาค่าต่ำสุดของ int และ float

using System; 
public class Demo { 
    public static void Main(){ 
        int val1 = 10, val2 = 15; 
        float val3 = 12.8f, val4 = 25.6f; 
        Console.WriteLine("Minimum Value from two int values = " + Math.Min(val1, val2)); 
        Console.WriteLine("Minimum Value from two float values = " + Math.Min(val3, val4)); 
    } 
}

ผลลัพธ์

Minimum Value from two int values = 10 
Minimum Value from two float values = 12.8