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

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

เมธอด Math.DivRem() ใน C# หารตัวเลขสองจำนวน คืนค่าผลหาร (Quotient) และส่งค่าเศษ (Remainder) ผ่านพารามิเตอร์ Output

ไวยากรณ์

public static int DivRem(int dividend, int divisor, out int remainder);
public static long DivRem(long dividend, long divisor, out long remainder);

ตัวอย่างที่ 1: Int

using System;

public class Demo
{
    public static void Main()
    {
        int dividend = 30;
        int divisor = 7;
        int remainder;
        
        int quotient = Math.DivRem(dividend, divisor, out remainder);
        
        Console.WriteLine("Quotient = " + quotient);
        Console.WriteLine("Remainder = " + remainder);
    }
}

ผลลัพธ์

Quotient = 4
Remainder = 2

ตัวอย่างที่ 2: Long (จำนวนใหญ่)

using System;

public class Demo
{
    public static void Main()
    {
        long dividend = 767676765765765;
        long divisor = 7;
        long remainder;
        
        long quotient = Math.DivRem(dividend, divisor, out remainder);
        
        Console.WriteLine("Quotient = " + quotient);
        Console.WriteLine("Remainder = " + remainder);
    }
}

ผลลัพธ์

Quotient = 109668109395109
Remainder = 2

ข้อดี: คำนวณผลหารและเศษพร้อมกันในครั้งเดียว ประหยัดการคำนวณซ้ำ (ปกติต้อง用 / และ % แยกกัน)