Help me understand this simple C program.

avi

Skilled
It all started with a question in Test Your C Skills with Yeshwant Kanetkar. Here is the actual question :

404443_4422955380630_1041211972_n.jpg

Code:
#include<stdio.h>
int main()
{
	float a=0.7;
	if(a<0.7)
	{
		printf("c\n");
	}
	else
	{
		printf("c++\n");
	}
	return 0;
}

I thought the output is 'C++', but the answer given as 'C'. So I ran the question in codepad, the answer is actually 'C'. C code - 14 lines - codepad

but when I changed the value of a to 1.7 or 2.7, I am getting output as 'C++'
code for 1.7 : C code - 14 lines - codepad
code for 2.7 : C code - 14 lines - codepad

When I checked the value stored, it was actually 0.69999 something, but not 0.7 !

Then I ran another program to print value of a float : http://codepad.org/er0zkzxS

Code:
#include<stdio.h>
int main()
{
float a=0.7, b=1.7, c=1.8, d=2.8;
printf("%.10f %.10f\n",0.7, a);
printf("%.10f %.10f\n",1.7, b);
printf("%.10f %.10f\n",1.8, c);
printf("%.10f %.10f\n",2.8, d);
return 0;
}

O/p:
Code:
0.7000000000 0.6999999881
1.7000000000 1.7000000477
1.8000000000 1.7999999523
2.8000000000 2.7999999523

So turns out float wasn't storing exact value. Instead it having value of 1.700000000000, it was having some extra digits at the end. However 1.8 was stored as 1.79999999 something.

It doesn't make sense to me at all. Why such behaviour ?
 
If you look at the the way floating point numbers are represented in binary, you'll understand that they're all approximations. In fact, comparing floating point numbers is considered a bad programming practice. There are some tricks around it, but this sort of comparison is never recommended.
 
In C and also in almost all C inherited families of the languages, when you want to use float values (raw values not float variables), always suffix it with the letter "f". In your case, the following if will work correctly if(a<0.7f)
 
Double will work in the example, but there are several examples where double would fail too. The fact is, any kind of floating point representation is an approximation and can throw up bugs in the most unexpected places. Using an 'epsilon' style comparison is usually more reliable, and there are other practices too which you can find.

That said, double is good enough for general purpose computing. But if you're writing code for scientific computing or financial applications, you should be very careful with your floats and doubles.
 
Back
Top