Tuesday, December 8, 2009

A program that helped me understand float!

I did not understand the storage of float in C/C++ until I have executed this program by accident.

#include<iostream.h>
#include<conio.h>

void main()
{
int i;
clrscr();
float f=0.7;
cout.precision(10);
cout<<f;
getch();
}

OUTPUT
0.6999999881

Now I understand the program

if(0.7f==0.7)
printf("I love you");
else
printf("I hate you");

The output is I hate you. I was under the false impression that it was due to the size. but it is not. It is due to the precision actually.

0.7=0.7000000000 which is not equal to 0.7f=0.6999999881!

Now it makes sense. I prepared so many questions like this for my Cognizant interview. But this is the only one that I remember now.

1 comment:

  1. Interesting blog as for me. I'd like to read more concerning that topic. Thanx for posting that info.
    Sexy Lady
    Russian Escorts London

    ReplyDelete

Thanks for commenting in my blog...