for-loop, increment by double

前端 未结 6 1092
渐次进展
渐次进展 2020-12-05 07:10

I want to use the for loop for my problem, not while. Is it possible to do the following?:

for(double i = 0; i < 10.0; i+0.25)

I want to

6条回答
  •  半阙折子戏
    2020-12-05 08:05

    James's answer caught the most obvious error. But there is a subtler (and IMO more instructive) issue, in that floating point values should not be compared for (un)equality.

    That loop is prone to problems, use just a integer value and compute the double value inside the loop; or, less elegant, give yourself some margin: for(double i = 0; i < 9.99; i+=0.25)

    Edit: the original comparison happens to work ok, because 0.25=1/4 is a power of 2. In any other case, it might not be exactly representable as a floating point number. An example of the (potential) problem:

     for(double i = 0; i < 1.0; i += 0.1) 
         System.out.println(i); 
    

    prints 11 values:

    0.0
    0.1
    0.2
    0.30000000000000004
    0.4
    0.5
    0.6
    0.7
    0.7999999999999999
    0.8999999999999999
    0.9999999999999999
    

提交回复
热议问题