0

When I compile and run the following code, x only gets printed when I initialize float x=1.5. It does not work for other values, for example, when I initialize float x=1.2 and write when(x==1.2), it does not print the value of x.

#include<stdio.h>
int main()
{
    float x=1.5;
    while (x==1.5)
    {
        printf("\n%f",x);
        x-=1;
    }
}

However, when I initialize float x=1.2f and write when(x==1.2f), the code runs as intended.

Also, if I declare and initialize x as double x=1.2, and write printf("\n%lf",x);, the code runs as intended.

This happens in both C and C++.

  • That sounds normal. A float converted to a double is probably not going to compare exactly equal to a number that started out as a double. – Shawn Nov 28 '21 at 09:15
  • This problem will occur for all numbers that cannot be stored exactly in a `float` variable. – Gerhardh Nov 28 '21 at 09:17
  • 1
    Try `if (x == 1.2f)`. Unlike `1.5`, `1.2` is not representable exactly in binary, so floats and doubles approximate it with different precision. By doing `x == 1.2` you're comparing a less precise float with a more precise double. – HolyBlackCat Nov 28 '21 at 09:19
  • @Shawn: A `float` converted to a `double` does not change value. The `float` values are a subset of the `double` values. A `double` value converted to `float` may be changed. – Eric Postpischil Nov 28 '21 at 09:30

1 Answers1

0

It tells the computer that this is a floating point number. If there is no f after the number, it is considered a double or an integer (depending on if there is a decimal or not).

3.0f -- float
3.0  -- double
3   --  integer
vegan_meat
  • 878
  • 4
  • 10
  • That is basically true, but does not explain why the issue happens. Also there is already a dublicate that explains it in great detail. – Gerhardh Nov 28 '21 at 09:20