當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


C# Decimal.Divide()用法及代碼示例


此方法用於將兩個指定的十進製值相除。

用法: public static decimal Divide (decimal a1, decimal a2);

參數:
a1:此參數指定股息。
a2:此參數指定除數。


返回值:a1除以a2的結果。

異常:

  • DivideByZeroException:當a2為零時發生。
  • OverflowException:如果將a1和a2相除的結果小於Decimal的最小可能值或大於Decimal的最大可能值。

以下示例程序旨在說明Decimal.Divide(Decimal,Decimal)方法的用法:

示例1:

// C# program to demonstrate the 
// Decimal.Divide(Decimal, 
// Decimal) Method 
using System; 
  
class GFG { 
  
    // Main Method 
    public static void Main() 
    { 
        try { 
  
            // Declaring the decimal variables 
            Decimal a1 = 4.02m; 
            Decimal a2 = 2.01m; 
  
            // dividing the two Decimal value 
            // using Divide() method; 
            Decimal value = Decimal.Divide(a1, a2); 
  
            // Display the division 
            Console.WriteLine("Result of "+ 
                 "division : {0}", value); 
        } 
  
        catch (OverflowException e)  
        { 
            Console.Write("Exception Thrown: "); 
            Console.Write("{0}", e.GetType(), e.Message); 
        } 
    } 
}
輸出:
Result of division : 2

示例2:溢出異常程序

// C# program to demonstrate the 
// Decimal.Divide(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.01m; 
  
            // dividing the two Decimal value 
            // using Divide() method; 
            Decimal value = Decimal.Divide(a1, a2); 
  
            // Display the division 
            Console.WriteLine("Result of "+ 
                  "division : {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.Divide(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 the two Decimal value 
            // using Divide() method; 
            Decimal value = Decimal.Divide(a1, a2); 
  
            // Display the division 
            Console.WriteLine("Result of"+ 
                " division : {0}", value); 
        } 
  
        catch (DivideByZeroException e) 
        { 
            Console.Write("Exception Thrown: "); 
            Console.Write("{0}", e.GetType(), e.Message); 
        } 
    } 
}
輸出:
Exception Thrown: System.DivideByZeroException

參考:



相關用法


注:本文由純淨天空篩選整理自IshwarGupta大神的英文原創作品 Decimal.Divide() Method in C#。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。