For-loop in C++ using double breaking out one step early, boundary value not reached

后端 未结 10 668
难免孤独
难免孤独 2020-12-06 03:24

I have a simple C++ program compiled using gcc 4.2.4 on 32-bit Ubuntu 8.04. It has a for-loop in which a double variable is incremented from zero t

10条回答
  •  旧巷少年郎
    2020-12-06 03:57

    As others have said, not every real number is exactly representable as a floating point value, so you can expect a small, "random" rounding error in floating-point calculations. It is similar to what happens with normal decimal digits: 1/3 isn't exactly representable using three decimal digits (0.33), so (1/3)*3 would become 0.99 and not exactly 1.

    It is possible to use some sort of "precision" in your comparisons, but I would recommend avoiding floating-point numbers for loops, and instead use integers.

    For example, your loop

    stepSize = 0.05;
    for (double index = rangeMin; index <= rangeMax; index+= stepSize)
    {
        cout << index << endl;
    }
    

    could be replaced by something along the lines of

    stepSize = 0.05;
    for (int index = 0; index < 21; ++index)
    {
        double value = rangeMin + index * stepSize;
        cout << value << endl;
    }
    

提交回复
热议问题