13
Math.IEEERemainder(x,y)和x%y?Math.IEEERemainder(x,y)是否等同于x%y?
Math.IEEERemainder(x,y)和x%y?Math.IEEERemainder(x,y)是否等同于x%y?
不,他们是不等价的。 MSDN示出了用于模和用于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)
一些实例,其中它们具有不同的/相同的输出(来自MSDN截取):
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
在相似的问题上,通过sixlettervariables查看这个好的answer。
不,他们不一样;请参阅documentation。
这里的源:
public static double IEEERemainder(double x, double y) {
double regularMod = x % y;
if (Double.IsNaN(regularMod)) {
return Double.NaN;
}
if (regularMod == 0) {
if (Double.IsNegative(x)) {
return Double.NegativeZero;
}
}
double alternativeResult;
alternativeResult = regularMod - (Math.Abs(y) * Math.Sign(x));
if (Math.Abs(alternativeResult) == Math.Abs(regularMod)) {
double divisionResult = x/y;
double roundedResult = Math.Round(divisionResult);
if (Math.Abs(roundedResult) > Math.Abs(divisionResult)) {
return alternativeResult;
}
else {
return regularMod;
}
}
if (Math.Abs(alternativeResult) < Math.Abs(regularMod)) {
return alternativeResult;
}
else {
return regularMod;
}
}
我只是想知道 - 为什么地球上我会想要这些结果? '11/3 = -1'?显然这里的模数是2.但是在什么情况下,我想'-1'? – 2015-10-01 16:05:39
@RoyiNamir您在这里有一个答案:http://stackoverflow.com/a/27378075/200443 – Maxence 2015-12-04 10:43:23