📜  C#中的Decimal.Remainder()方法

📅  最后修改于: 2021-05-29 19:55:34             🧑  作者: Mango

当在两个指定的十进制值之间进行除法时,使用此方法来计算余数。

例外情况:

  • DivideByZeroException:当a2为零时发生。
  • OverflowException:如果返回值小于MinValue或大于MaxValue

下面的程序说明了Decimal.Remainder(Decimal,Decimal)方法的用法:

范例1:

// C# program to demonstrate the
// Decimal.Remainder(Decimal, 
// Decimal) Method
using System;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
        try {
  
            // Declaring the decimal variables
            Decimal a1 = 4.02m;
            Decimal a2 = 1.11m;
  
            // dividing and getting the remainder
            // of the two Decimal value
            // using Remainder() method;
            Decimal value = Decimal.Remainder(a1, a2);
  
            // Display the remainder
            Console.WriteLine("Remainder is : {0}", value);
        }
  
        catch (OverflowException e) 
        {
            Console.Write("Exception Thrown: ");
            Console.Write("{0}", e.GetType(), e.Message);
        }
    }
}
输出:
Remainder is : 0.69

示例2:对于OverflowException

// C# program to demonstrate the
// Decimal.Remainder(Decimal, 
// Decimal) Method
using System;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
        try {
  
            // Declaring the decimal variables
            Decimal a1 = Decimal.MaxValue;
            Decimal a2 = 0.02m;
  
            // dividing and getting the remainder
            // of the two Decimal value
            // using Remainder() method;
            Decimal value = Decimal.Remainder(a1, a2);
  
            // Display the remainder
            Console.WriteLine("Remainder is : {0}", value);
        }
  
        catch (OverflowException e) 
        {
            Console.Write("Exception Thrown: ");
            Console.Write("{0}", e.GetType(), e.Message);
        }
    }
}
输出:
Exception Thrown: System.OverflowException

示例3: DivideByZeroException程序

// C# program to demonstrate the
// Decimal.Remainder(Decimal,
// Decimal) Method
using System;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
        try {
  
            // Declaring the decimal variables
            Decimal a1 = 4.02m;
            Decimal a2 = 0.00m;
  
            // dividing and getting the remainder
            // of the two Decimal value
            // using Remainder() method;
            Decimal value = Decimal.Remainder(a1, a2);
  
            // Display the remainder
            Console.WriteLine("Remainder is : {0}", value);
        }
  
        catch (DivideByZeroException e) 
        {
            Console.Write("Exception Thrown: ");
            Console.Write("{0}", e.GetType(), e.Message);
        }
    }
}
输出:
Exception Thrown: System.DivideByZeroException

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.decimal.remainder?view=netframework-4.7.2