Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
312 views
in Technique[技术] by (71.8m points)

c# - How does modulus operation works with float data type?

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

Another example using decimal data types:

decimal p=10;
decimal q=40;
result=p%q;

getting answer=20.

I am not understanding how does modulus works?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...