How does DoubleUtil.DoubleToInt(double val) work?

我的梦境 提交于 2019-12-07 19:18:22

问题


The MS.Internal.DoubleUtil-Class contains the function

public static int DoubleToInt(double val)
{
    return (0 < val) ? (int)(val + 0.5) : (int)(val - 0.5);
}

I wonder why this 'converts' val to an Integer?


回答1:


The cast from double to int always takes the floor, so adding .5 (or subtracting .5 if it is negative) means 1.6 returns 2, while 1.4 would return 1.




回答2:


For numbers > 0 it adds 0.5 and truncates. For numbers < 0 it subtracts 0.5 and truncates.

The (int) cast in fact truncates, so (int)7.8 == 7, (int)-7.8 == 7, (int)7.995 == 7 and so on.

So we have:

0-0.499999... is rounded to 0 (0.499999 + 0.5 == 0.999999 trucated == 0)
0.5-1... is rounded to 1 (1 + 0.5 == 1.5 truncated == 1) 

and so on.

The opposite for negative numbers.

Border cases (values outside the int.MinValue - int.MaxValue range) are probably ignored, so are Double special values (NaN, PositiveInfinity, NegativeInfinity)

There could be some problems with some double numbers, because double aren't "precise" (it's complex to explain, try looking for why the double are bad) and often what you see is not what you have, so you could have something you think is 1.5 but in reality is 1.499999999999985 and so it's rounded to 1 instead of 2.

Something like:

double d = 11.3;

// There are 20x += 0.01 
d += 0.01; d += 0.01; d += 0.01; d += 0.01; d += 0.01;
d += 0.01; d += 0.01; d += 0.01; d += 0.01; d += 0.01;
d += 0.01; d += 0.01; d += 0.01; d += 0.01; d += 0.01;
d += 0.01; d += 0.01; d += 0.01; d += 0.01; d += 0.01;

Console.WriteLine("{0}", d);
Console.WriteLine("{0:R}", d);
Console.WriteLine("{0}", DoubleToInt(d));

result:

11.5
11.499999999999996
11



回答3:


This is simply because it casts to (int). The + or - is simply used to round the value.



来源:https://stackoverflow.com/questions/18102656/how-does-doubleutil-doubletointdouble-val-work

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!