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

后端 未结 10 705
难免孤独
难免孤独 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:50

    You should not use == or <= for doubles due to its internal representation. On last step you'll get 0.95000000000000029. Instead you could use the following code:

    stepSize = 0.05;
    // stepSize/2 looks like a good delta for most cases
    for (double index = rangeMin; index < rangeMax+stepSize/2; index+= stepSize)
    {
        cout << index << endl;
    }
    

    For more details read What Every Computer Scientist Should Know About Floating-Point Arithmetic.

提交回复
热议问题