double or float datatype doesn't addup properly in a loop?

后端 未结 5 998
春和景丽
春和景丽 2020-12-12 03:37

In a loop I am adding 0.10 till I reach the desired #, and getting the index. This is my code :

    private static int getIndexOfUnits(float units) {
    int         


        
5条回答
  •  生来不讨喜
    2020-12-12 04:19

    You shouldn't use float's for this kind of thing (indexing / iterating).

    Try calculating I every time:

    I = 1.0f + (i*addup);
    

    And you'll not accumulate floating-point errors.

提交回复
热议问题