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

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
O/p:
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 ?

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 ?