0
#include<stdio.h>

void main( )

{

    float x=3.14;

    if (x == 3.14)

    printf("Computers Science");

    else 

    printf("Information Technology");

}

Um... Can you help me why ?? Just answer why okay thanks I am not clear why it is happening i am a beginner and this is... Pls help

  • `float x=3.14f; if (x == 3.14f)` _or_ `double x=3.14;` should fix this particular case, as the source code literal should be deterministically converted to binary, 3.14 is the same double every time, and 3.14f is the same float every time. – hyde Dec 07 '22 at 05:31
  • 14/100 is a periodic number in binary just like 1/3 is periodic in decimal. So it can't be stored accurately as a floating point number. If your environment is like mine, the closest `float` is 3.1400001049041748046875. But you compare this to a `double`. The closest `double` is 3.140000000000000124344978758017532527446746826171875. It would produce the desired output if you use `float` values throughout, or `double` values throughout (as per the earlier comment). – ikegami Dec 07 '22 at 05:39
  • The root of the problem is the sloppy mixing of float and double types. If `3.14` can't be exactly represented in `float` then you'll get a certain amount of decimals. However, the constant `3.14` without `f` in the end is of type `double`, with a greater amount of decimals. When the float `x` and the `double` `3.14` are used in the same `==` expression, `x` gets converted to `double` _but the value is preserved_. Since the amount of decimals are different, the numbers aren't equal. One of several reasons why floating point numbers should never be compared for equality. – Lundin Dec 07 '22 at 11:58

0 Answers0