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

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

    This is due to the inexact representation of decimal fractions by floating-point numbers. Your step size isn't actually 0.1 or 0.05, it's some other value that's very close. The slight error accumulates as you go through the loop.

    To solve this problem, you have to avoid comparing floating-point numbers for equality.

提交回复
热议问题