Why does for loop using a double fail to terminate

前端 未结 5 1027
走了就别回头了
走了就别回头了 2020-12-07 00:20

I\'m looking through old exam questions (currently first year of uni.) and I\'m wondering if someone could explain a bit more thoroughly why the following for l

5条回答
  •  南方客
    南方客 (楼主)
    2020-12-07 01:12

    As a general rule, never use double to iterate with due to rounding errors (0.1 may look nice when written in base 10, but try writing it in base 2—which is what double uses). What you should do is use a plain int variable to iterate and calculate the double from it.

    for (int i = 0; i < 1000; i++)
      System.out.println(i/10.0);
    

提交回复
热议问题