0
#include<stdio.h>
int main()
{
    float x=0;
    while(x<=.2)
    {
        printf("%f\n",x);
        x=x+0.2;
    }
    return 0;
}

The output is

0.000000

But it should give..

0.000000
0.200000

I am posting question on stackoverflow for the first time. Please forgive me for my silliness.

  • Note too that you are mixing `float` (x) and `double` (0.2). – Weather Vane Apr 05 '18 at 15:08
  • 4
    The linked answer doesn't fully explain things. in this case, x is a float (single precision). 0.2 is a double. Changing the type of x to double, or replacing the add line with x = x + 0.2f should solve the problem. – luckykaa Apr 05 '18 at 15:09
  • Thanks. @ Weather Vane, I didn't know there are these problems with storing floating point data. Is there a simple way to solve the situation. I actually don't want to go that deep. I only need to the variable x to go from 0 to 0.6 (say) with steps 0.2. But it only goes to 0.4.I am editing the quetion to clarify in what situation I am facing the problem. And I need s simple solution. (I am not a programing student :( ) – Siddhartha Apr 05 '18 at 15:23
  • @luckykaa Thanks. I read your comment later. I guess no need to edit the question. Thank you. – Siddhartha Apr 05 '18 at 15:25
  • 1
    @Siddhartha if you need exact values, use integers, e.g. `for (int x = 0; x < 4; ++x) { printf("%f", x * .2); }` –  Apr 05 '18 at 15:25
  • You should avoid using equality operators with `float` and `double` (including `<=` and `>=`). Check this question and the linked questions: https://stackoverflow.com/questions/13249796/comparing-float-variable – giusti Apr 05 '18 at 15:25
  • 1
    @luckykaa I wouldn't call this a solution, testing for equality will still go wrong in many cases. The duplicate explains quite well what the general problem is and how to avoid it –  Apr 05 '18 at 15:27
  • use while(x<=.2f), as by default .2 is double not float. – Monk Apr 05 '18 at 15:36
  • 1
    @luckykaa: While those changes would fix this one specific sample, it will not fix the problem if more additions are performed, as they will incur multiple rounding errors during repeated additions, rather than just one rounding error from the type conversion. – Eric Postpischil Apr 05 '18 at 15:48
  • We've given you a simple solution: don't expect "==" (or the equal part of <=, >=) to be useful or predictable with floats. If you need floats, don't use ==. If you need exact loop counts, don't use floats. – Lee Daniel Crocker Apr 05 '18 at 18:16

0 Answers0