in Programming in C
1,137 views
1 vote
1 vote
#include
int main(){
    float x = 0.1;
    if (x == 0.1)
        printf("IF");
    else if (x == 0.1f)
        printf("ELSE IF");
    else
        printf("ELSE");
    return 0;
}

#include
int main{
    float x = 0.5;
    if (x == 0.5)
        printf("IF");
    else if (x == 0.5f)
        printf("ELSE IF")
    else
        printf("ELSE");
    return 0;
}

First program Output: ELSE IF
Second program Output: IF

Both programs are similar.But outputs are different.Why?
in Programming in C
by
1.1k views

1 Answer

0 votes
0 votes
I tried the following code segment to get the exact representation of 0.1 & 0.5 being used by my machine:

#include<stdio.h>
int main(void)
{
    float a = 0.1;
    float b = 0.5;
    printf("%x\n",*(int*)&a); /*Prints the value of 0.1 as stored by computer in hexadecimal format.*/
    printf("%x\n",*(int*)&b); /*Prints the value of 0.5 as stored by computer in hexadecimal format.*/
    return 0;
}

& got the following out put

-----------------------------------------

3dcccccf

3f000000

--------------------------------

It means that it stores 0.1 as 3dcccccf and 0.5 as 3f000000.

On converting this values back to the float using IEEE Floating Point Representation 754 I got 0.09999999404 & 0.5.

It means that 0.1 can not be EXACTLY represented using 32 bit floating point, but 0.5 can be represented.

So output for 0.1 should be ELSE IF &

output for 0.5 should be IF.

2 Comments

that's the key point but there's something remaining. Even if representation isn't exact, it always remains the same. But 0.1 or any real number is by default taken as "double" in C. And this causes the equality to fail for numbers which cannot be exactly represented within the float limit. If we use 0.1f, then comparison will be true.
0
0
It means that double precision floating point will just represent 0.1 more precisely, but not exactly.

Thank you sir.I was not sure about it so I did not mentioned it in the answer. :)
0
0

Related questions