edited by
480 views
0 votes
0 votes
int main()
{
    float f=0.7;
    if(f==0.7)
    printf("equal");
    else
    printf("not equal");
    return 0;
}                                                                                                                                                                                    what will be the o/p and why? plz explain
edited by

2 Answers

Best answer
5 votes
5 votes

You might feel that the answer is equal but unfortunately, the answer seems to be not equal. Why?

Let's see.

You know IEEE 754 standards right.
If you convert 0.7 to binary, then you cannot represent it exactly. This is where the problem creeps in...

(0.7)_10=(0.1 0110 0110 0110 0110 0110 0110 0110...)_2

Now in C, real constants are treated to be double literals. As such they have much higher precision [52 bits for the mantissa] than floating-point number [23 bits in the mantissa]

So 0.7 is a more accurate 0.7 than 0.7f

Now you are correct that during comparison the float is promoted to double, but the extra bits in the mantissa is filled with 0s. So (double)0.7f < 0.7

#include <stdio.h>
int main()
{
  printf("%.70f \n%.70f\n",0.7f,0.7);
}

$ ./a.out
0.6999999880790710449218750000000000000000000000000000000000000000000000 
0.6999999999999999555910790149937383830547332763671875000000000000000000


Credit: @Hitech Ga

0 votes
0 votes
Here, when you assign the value as 0.15 to variable f , it takes it as 0.15 itself. While when you directly declare as constant then it becomes 0.1534585657… so on. It’s basically architecture and range specific. Try putting f=0.15 as it is and change 0.15 (directly declared constant) to 0.15f, the output would be “equal”.

No related questions found