当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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#。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。