1

Here's a code that i want to discuss

#include<stdio.h>
int main()
{
    float a=0.1;
    if(a==0.1)
        printf("Stack");
    else
        printf("OverFlow");
    return 0;
}

output :

OverFlow

Can i have an explanation of this output ? in my perspective i think that my machine couldn't find the binary representation of 0.1 (because the binary of 0.1is an infinite number), is my intuition correct?

Michael Dorgan
  • 12,453
  • 3
  • 31
  • 61
LEARNER
  • 123
  • 1
  • 9
  • 2
    You're comparing a `float` `0.1` to a `double` `0.1`. Since `0.1` cannot be exactly represented as a floating point number, the `double` version is more accurate and hence not equal to the `float` version. – Tom Karzes Jun 10 '20 at 18:18
  • 1
    `if(a == (float)0.1)` outputs `Stack` – Cid Jun 10 '20 at 18:20
  • 1
    Read up on floating point math. In general, it is not possible to directly compare for equality on a floating point number and an epsilon value (+/- value) is generally applied. – Michael Dorgan Jun 10 '20 at 18:20
  • 1
    https://stackoverflow.com/questions/4915462/how-should-i-do-floating-point-comparison – Michael Dorgan Jun 10 '20 at 18:22
  • The intuition was right, `1/10` recurs, as does `1/7` in decimal, but the approximation would have been consistent if you hadn't used different (`float` and `double`) representations of `0.1` which is of type `double`. – Weather Vane Jun 10 '20 at 18:22
  • `float a=0.1;` -> `double a=0.1;` and then try again – Jabberwocky Jun 10 '20 at 18:27
  • For more insight `printf("%.20f %.20f\n", 0.1, 0.1f);` – chux - Reinstate Monica Jun 10 '20 at 18:41

0 Answers0