1,144 views
1 votes
1 votes
#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?

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.

Related questions

0 votes
0 votes
0 answers
1