📜  C#中的MathF.IEEERemainder()方法与示例

📅  最后修改于: 2021-05-30 01:16:57             🧑  作者: Mango

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

返回类型:此方法返回一个等于x –( y Q)的数字,其中Qx / y的商,四舍五入为最接近的System.Single类型的整数。

笔记:

  • 如果x / y介于两个整数之间,则返回偶数整数。
  • 如果x –( y Q)为零,则如果x为正,则返回正零;如果y为负,则返回负零。
  • 如果y = 0,则返回NaN

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

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

余数运算符的公式为:

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

例子:

// C# Program to illlustrate the use of
// MathF.IEEERemainder(Single, Single)
// Method
using System;
  
class Geeks {
  
    // Method to calculate the remainder
    private static void DisplayRemainder(float x,
                                        float y)
    {
  
        var calculation = $"{x} / {y} = "; 
  
        // calculating IEEE Remainder
        var ieeerem = MathF.IEEERemainder(x, y);
  
        // using remainder operator
        var rem_op = x % y;
  
        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(0f, 1f);
        DisplayRemainder(-4f, 8f);
        DisplayRemainder(1f, 0f);
        DisplayRemainder(-1f, -0f);
        DisplayRemainder(175f, 6f);
        DisplayRemainder(784.52f, 124f);
        DisplayRemainder(92.267f, 3.259f);
    }
}
输出:
IEEERemainder   Remainder Operator
0 / 1 =                           0                    0
-4 / 8 =                         -4                   -4
1 / 0 =                         NaN                  NaN
-1 / 0 =                        NaN                  NaN
175 / 6 =                         1                    1
784.52 / 124 =             40.52002             40.52002
92.267 / 3.259 =            1.014997             1.014997