Welcome to Atlanta .NET Regular Guys Sign in | Join | Help

Float to Int conversions by Greg Young

Greg Young pinged me via IM to show me a problem he's run into - a bug in the C# compiler.  Open up Visual Studio and start a C# console app.  Paste the following code into the Main routine:

float low = 7f;
float high = 100f;
low = ((high + low) / 2f);
low = ((high + low) / 2f);
low = ((
int)(low * 100f)) / 100f;
low = ((high + low) / 2f);
low = ((
int)(low * 100f)) / 100f;
low = ((high + low) / 2f);
low = ((
int)(low * 100f)) / 100f;
low = ((high + low) / 2f);
low = ((
int)(low * 100f)) / 100f;
Console.WriteLine(low);
Console.ReadLine();

Press F5 to run with the debugger.  Get a result.  Press CTRL+F5 to run without the debugger.  Get a different result.  Here is Greg's writeup of the problem.

Greg's already submitted this to Microsoft.

Published 30-05-2006 08:54 by Matt Ranlett
Filed Under:

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

 

El Guapo said:

I could have saved you time with this guaranteed reponse : This Is Not A Bug
May 30, 2006 10:38 AM
 

Greg Young said:

You are correct. As I say in my post it is not a bug.

It is however a breaking change from 1.x. My emails to MS have actually been suggesting a compiler switch for predictable floating point operations (in fact I went so far as to suggest that it be turned on by default).
June 1, 2006 8:50 AM

What do you think?

(required) 
(optional)
(required) 

About Matt Ranlett

One of the two original Atlanta .NET Regular Guys, Matt fills his free time by helping to run several Atlanta area user groups, the Atlanta Code Camps, and works as one of the two INETA co-Vice Presidents of Technology
SkinName:iroha_Blog2
Powered by Community Server, by Telligent Systems