251 views
3 votes
3 votes
#include <stdio.h>
#include <string.h>
int main()
{
 float a = 1.5;
 if(a == 1.5)
        printf("Hello");
    printf("_World");
    return 0;
}

output of the above code  is :Hello_World

#include <stdio.h>
#include <string.h>
int main()
{
 float a = 1.45;
 if(a == 1.45)
        printf("Hello");
    printf("_World");
    return 0;
}

output of above code is:_World

Can anyone please explain the concept behind it?

1 Answer

Best answer
4 votes
4 votes

Try double it would execute:- 

Actually, float and double are two different data types in C for storing real numbers. double occupies twice the memory occupied by float.

as you are comparing 1.5 and 1.5 is converted into binary as 

for 1 it is simple 00000001(depends on your machine architecture)

for 0.5

=2*0.5=1 ->1(so again same like previous 1)

While storing this value in float variable, all bits are accepted.

but in 1.45

same for 1(like previously) 

0.45 * 2 = 0.9 ->0

0.9 * 2 = 1.8 -> 1

0.8 * 2 = 1.6 -> 1

0.6 * 2 = 1.2 -> 1

0.2 * 2 = 0.4 -> 0

0.4 * 2 = 0.8 -> 0

0.8 * 2 = 1.6 -> 1

0.6 * 2 = 1.2 -> 1

0.2 * 2 = 0.4 -> 0

and so on...

While storing this value in float variable, only some bits are stored, depending on the size of float variable, and rest are discarded. So the number stored is bit smaller than 1.45 itself. And hence the comparison fails.

so in the case of 1.5 :-  print Hello_World

in the case of 1.45 :-  print  _World

selected

Related questions

0 votes
0 votes
0 answers
4