How does modulus operation works with float data type?

这一生的挚爱 提交于 2019-11-28 00:11:49

From the C# language spec on floating point remainder. In the case of x % y if x and y are positive finite values.

z is the result of x % y and is computed as x – n * y, where n is the largest possible integer that is less than or equal to x / y.

The C# language spec also clearly outlines the table of what to do with the cases of all possible combinations of nonzero finite values, zeros, infinities, and NaN’s which can occur with floating point values of x % y.

                          y value

                | +y  –y  +0  –0  +∞  –∞  NaN
           -----+----------------------------  
  x         +x  | +z  +z  NaN NaN x   x   NaN
            –x  | –z  –z  NaN NaN –x  –x  NaN
  v         +0  | +0  +0  NaN NaN +0  +0  NaN
  a         –0  | –0  –0  NaN NaN –0  –0  NaN
  l         +∞  | NaN NaN NaN NaN NaN NaN NaN
  u         –∞  | NaN NaN NaN NaN NaN NaN NaN
  e         NaN | NaN NaN NaN NaN NaN NaN NaN

This article on msdn has sufficient example but I can explain it real quick;

http://msdn.microsoft.com/en-us/library/0w4e0fzs.aspx

If you do int result = x % y; what you'll find is that you are returned the remainder of x % y and the values are treated more like whole numbers. For example, the third line in the link is Console.WriteLine(5.0 % 2.2); which prints .6. This is because it finds that 2.2 can go into 5.0 no more than twice. So it does 5 - 2.2(2) which is .6

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