📜  C#| Math.IEEERemainder()方法

📅  最后修改于: 2021-05-29 20:39:43             🧑  作者: Mango

在C#中, IEEERemainder()是Math类方法,用于返回将指定数字除以另一个指定数字所得的余数。

句法:

public static double IEEERemainder (double a, double b);

参数:

返回类型:此方法返回等于a –( b Q)的数字,其中Qa / b的商,四舍五入为最接近的System.Double类型的整数。

笔记:

  • 如果a / b介于两个整数之间,则返回偶数整数。
  • 如果一个(B Q)是零,则返回值模型正零,如果是正的,零或负零,如果是负的。
  • 如果b = 0,则返回NaN

IEEERemainder和Remainder运算符之间的区别:两者都用于除法后返回余数,但是它们使用的公式不同。 IEEERemainder方法的公式为:

IEEERemainder = dividend - (divisor * Math.Round(dividend / divisor))

余数运算符的公式为:

Remainder = (Math.Abs(dividend) - (Math.Abs(divisor) *  
            (Math.Floor(Math.Abs(dividend) / Math.Abs(divisor))))) *   
            Math.Sign(dividend)

例子:

// C# Program to illlustrate the
// Math.IEEERemainder() Method
using System;
  
class Geeks
{
      
   // method to calucalte the remainder 
   private static void DisplayRemainder(double num1, double num2)
   {
         
      var calculation = $"{num1} / {num2} = ";
        
      // calculating IEEE Remainder
      var ieeerem = Math.IEEERemainder(num1, num2);
        
      // using remainder operator
      var rem_op = num1 % num2;
        
      Console.WriteLine($"{calculation,-16} {ieeerem,18} {rem_op,20}");
   }
     
     
     
   // Main Method
   public static void Main()
   {
         
      Console.WriteLine($"{"IEEERemainder",35} {"Remainder Operator",20}");
        
      // calling the method
      DisplayRemainder(0, 1);
      DisplayRemainder(-4, 8);
      DisplayRemainder(1, 0);
      DisplayRemainder(-1, -0);
      DisplayRemainder(145, 7);
      DisplayRemainder(18.52, 2);
      DisplayRemainder(42.26, 4.2);
   }
}

输出:

IEEERemainder   Remainder Operator
0 / 1 =                           0                    0
-4 / 8 =                         -4                   -4
1 / 0 =                         NaN                  NaN
-1 / 0 =                        NaN                  NaN
145 / 7 =                        -2                    5
18.52 / 2 =                    0.52                 0.52
42.26 / 4.2 =     0.259999999999998    0.259999999999996

参考: https : //docs.microsoft.com/zh-cn/dotnet/api/system.math.ieeeremainder?view=netframework-4.7.2