How does modulus operation works with float data type?

后端 未结 2 1502
南笙
南笙 2020-12-03 15:07

I m trying to find out a simple modulus operation on float data type.

float a=3.14f;
float b=10f;
result=a%b;

I m getting result= 3.14

相关标签:
2条回答
  • 2020-12-03 15:43

    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
    
    0 讨论(0)
  • 2020-12-03 15:45

    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

    0 讨论(0)
提交回复
热议问题