If you have ever worked with arithmetical operations in C# you probably know this. But it is the thing that can easily be slept from you and not even mentioned.
What do you think the code will print? True or False?
The result is, of course, FALSE. You should never forget the TYPE. Integer 5 divided by integer 2 returns INTEGER. And it is truncated integer, so the value will be 2 and not 2.5.
This fact that division operator returns INTEGER in my opinion is just wrong. There is no ANY guarantee at all that result will ever be integer. In other languages (including Pascal/Delphi) the division returns floating-point result. Which IS correct.
So in real live: INT/INT=REAL, in C# INT/INT=INT. Just wrong. No math behind such kind of division.
I have just faced this issue (just totally forgot about INT/INT=INT) trying to calculate an angle between 2 points on the Bitmap. It is simple:
So you should remember once and forever: Be explicit about type when using division.
And the code snippets should look like this to work correctly:
Additional note is that ReSharper greatly warns you saying “Possible loss of fraction”. I love it more and more every day.
What do you think the code will print? True or False?
Console.WriteLine(5/2 > 2); // True or False?
This fact that division operator returns INTEGER in my opinion is just wrong. There is no ANY guarantee at all that result will ever be integer. In other languages (including Pascal/Delphi) the division returns floating-point result. Which IS correct.
So in real live: INT/INT=REAL, in C# INT/INT=INT. Just wrong. No math behind such kind of division.
I have just faced this issue (just totally forgot about INT/INT=INT) trying to calculate an angle between 2 points on the Bitmap. It is simple:
Point p1 = GetIt(); Point p2 = GetIt(); var radians = Math.Atan( (p1.X-p2.X) / (p2.Y-p1.Y) ); // Atan( INT/INT)!!As we can see the error is unavoidable. We will end up with wrong result.
So you should remember once and forever: Be explicit about type when using division.
And the code snippets should look like this to work correctly:
Console.WriteLine(5.0/2.0 > 2.0); // This correctly becomes "True" // casting of one division argument is enough, but better be explicit Math.Atan( (double)(p1.X-p2.X) / (double)( p2.Y-p1.Y) ); // or if casting bothers you: Math.Atan( (0.0 + p1.X-p2.X) / (0.0 + p2.Y-p1.Y) );
Additional note is that ReSharper greatly warns you saying “Possible loss of fraction”. I love it more and more every day.