返回一指定数字被另一指定数字相除的余数。
public static double IEEERemainder(
double x,
double y
)
参数:
x
类型:System.Double
被除数。
y
类型:System.Double
除数。
返回值:
类型:System.Double
该数等于 x - (y * Q),其中 Q 是 x / y 的商的最接近整数(如果 x / y 在两个整数中间,则返回偶数)。
如果 x - (y * Q)为零,则在 x 为正时返回值 +0,而在 x 为负时返回 -0。
如果 y 等于 0,则返回 NaN。
备注:
此操作遵守电气和电子工程师协会于 1985 年制定的 IEEE 二进制浮点数算术标准、ANSI/IEEE 标准 754-1985 第 5.1 节中定义的余数运算。
IEEERemainder 方法与取模运算符不同。虽然这两者都返回相除后的余数,但它们使用的公式不同。
IEEERemainder 方法的公式为:
IEEERemainder = dividend - (divisor * Math.Round(dividend / divisor))
相比而言,取模运算符的公式为:
Modulus = (Math.Abs(dividend) - (Math.Abs(divisor) *
(Math.Floor(Math.Abs(dividend) / Math.Abs(divisor))))) *
Math.Sign(dividend)
示例:
下面的示例将 IEEERemainder 方法返回的余数与模数除法运算符返回的余数作比较。
using System;
public class Example
{
public static void Main()
{
Console.WriteLine("{0,35} {1,20}", "IEEERemainder", "Modulus");
ShowRemainders(3, 2);
ShowRemainders(4, 2);
ShowRemainders(10, 3);
ShowRemainders(11, 3);
ShowRemainders(27, 4);
ShowRemainders(28, 5);
ShowRemainders(17.8, 4);
ShowRemainders(17.8, 4.1);
ShowRemainders(-16.3, 4.1);
ShowRemainders(17.8, -4.1);
ShowRemainders(-17.8, -4.1);
}
private static void ShowRemainders(double number1, double number2)
{
string formula = String.Format("{0} / {1} = ", number1, number2);
Console.WriteLine("{0,-16} {1,18} {2,20}",
formula,
Math.IEEERemainder(number1, number2),
number1 % number2);
}
}
// The example displays the following output:
//
// IEEERemainder Modulus
// 3 / 2 = -1 1
// 4 / 2 = 0 0
// 10 / 3 = 1 1
// 11 / 3 = -1 2
// 27 / 4 = -1 3
// 28 / 5 = -2 3
// 17.8 / 4 = 1.8 1.8
// 17.8 / 4.1 = 1.4 1.4
// -16.3 / 4.1 = 0.0999999999999979 -4
// 17.8 / -4.1 = 1.4 1.4
// -17.8 / -4.1 = -1.4 -1.4
原文中链接地址:http://msdn.microsoft.com/zh-cn/library/system.math.ieeeremainder.aspx#Y142