Home > C++, VC++ > Comparing two float values

Comparing two float values

I’ve heard people say that they don’t get expected results when comparing two float numbers…

One of the reasons that I found is this…

const float fSomeFloat = 0.2;
if( fSomeFloat == 0.2 )
{
  printf( "The two floating point numbers are equal, blah\n" );
}

This is bad programming, if condition won’t return true. 😐

The reason being that when you write 0.2 in the editor it’s treated as double instead of a float. So always suffix ‘f’ with floating point numbers.

const float fSomeFloat = 0.2f;
if( fSomeFloat == 0.2f )
{
  printf( "The two floating point numbers are equal, blah\n" );
}

Now if condition will return true, hence printing the above statement. Note that the first ‘f’ when assigning to a float can be avoided since it will be converted to float but the second is mandatory when comparing with another float. But as I said, ( see I am jumping up and down and again and again… ) always suffix ‘f’ with floating point numbers.

The same with longs, unsigned longs. If you write 1, 2, 4, etc in the editor it’s treated as an integer so if you want them to be treated as longs and unsigned longs suffix these numbers with ‘l’ and ‘ul’. With integers you won’t know the difference, with real numbers you will have trouble. So practice this always.

For eg:

const long lSomeLong = 12312L; or 12312l
const unsigned long ulSomeLong = 1231UL; or 1231ul;
const int16 i16Val = 212I16;
const int32 i32Val = 212I32;
const int64 i64Val = 212I64;
Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: